wp_schedule_event()
云策文档标注
概述
wp_schedule_event() 是 WordPress 中用于安排重复性事件的函数,它基于指定的时间间隔触发一个 Hook。事件会在有用户访问站点且计划时间已过时执行。
关键要点
- 函数用于安排重复性事件,接受时间戳、重复频率、Hook 名称和可选参数。
- 重复频率的有效值包括 'hourly'、'twicedaily'、'daily' 和 'weekly',可通过 'cron_schedules' 过滤器扩展。
- 使用 wp_next_scheduled() 防止重复安排事件,wp_schedule_single_event() 用于安排非重复事件。
- 参数 $args 是一个数组,用于传递给 Hook 回调函数,数组键被忽略。
- 返回值在成功时为 true,失败时为 false 或 WP_Error(取决于 $wp_error 参数)。
- 函数内部使用 _get_cron_array() 和 _set_cron_array() 管理 cron 数组。
- 提供了 'pre_schedule_event' 和 'schedule_event' 过滤器,允许插件干预事件安排。
代码示例
// 安排每小时事件,带参数检查
register_activation_hook( __FILE__, 'my_activation' );
function my_activation() {
$args = array( $args_1, $args_2 );
if (! wp_next_scheduled( 'my_hourly_event', $args )) {
wp_schedule_event( time(), 'hourly', 'my_hourly_event', $args );
}
}
add_action( 'my_hourly_event', 'do_this_hourly', 10, 2 );
function do_this_hourly($args_1, $args_2) {
// 每小时执行的操作
}
register_deactivation_hook( __FILE__, 'my_deactivation' );
function my_deactivation() {
wp_clear_scheduled_hook( 'my_hourly_event', array($args_1, $args_2) );
}注意事项
- 安排事件时,建议在插件激活钩子中调用,并使用 wp_next_scheduled() 避免重复。
- 清理计划事件时,wp_clear_scheduled_hook() 需要传递与安排时相同的参数数组。
- 对于资源密集型任务,考虑禁用 WordPress 内部 CRON 并使用外部 cron 作业。
- 使用自定义重复频率时,确保在添加 'cron_schedules' 过滤器后调用 wp_schedule_event()。
原文内容
Schedules a recurring event.
Description
Schedules a hook which will be triggered by WordPress at the specified interval.
The action will trigger when someone visits your WordPress site if the scheduled time has passed.
Valid values for the recurrence are ‘hourly’, ‘twicedaily’, ‘daily’, and ‘weekly’.
These can be extended using the ‘cron_schedules’ filter in wp_get_schedules() .
Use wp_next_scheduled() to prevent duplicate events.
Use wp_schedule_single_event() to schedule a non-recurring event.
Parameters
$timestampintrequired-
Unix timestamp (UTC) for when to next run the event.
$recurrencestringrequired-
How often the event should subsequently recur.
See wp_get_schedules() for accepted values. $hookstringrequired-
Action hook to execute when the event is run.
$argsarrayoptional-
Array containing arguments to pass to the hook’s callback function. Each value in the array is passed to the callback as an individual parameter.
The array keys are ignored.Default:
array() $wp_errorbooloptional-
Whether to return a WP_Error on failure.
Default:
false
Source
function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array(), $wp_error = false ) {
// Make sure timestamp is a positive integer.
if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
if ( $wp_error ) {
return new WP_Error(
'invalid_timestamp',
__( 'Event timestamp must be a valid Unix timestamp.' )
);
}
return false;
}
$schedules = wp_get_schedules();
if ( ! isset( $schedules[ $recurrence ] ) ) {
if ( $wp_error ) {
return new WP_Error(
'invalid_schedule',
__( 'Event schedule does not exist.' )
);
}
return false;
}
$event = (object) array(
'hook' => $hook,
'timestamp' => $timestamp,
'schedule' => $recurrence,
'args' => $args,
'interval' => $schedules[ $recurrence ]['interval'],
);
/** This filter is documented in wp-includes/cron.php */
$pre = apply_filters( 'pre_schedule_event', null, $event, $wp_error );
if ( null !== $pre ) {
if ( $wp_error && false === $pre ) {
return new WP_Error(
'pre_schedule_event_false',
__( 'A plugin prevented the event from being scheduled.' )
);
}
if ( ! $wp_error && is_wp_error( $pre ) ) {
return false;
}
return $pre;
}
/** This filter is documented in wp-includes/cron.php */
$event = apply_filters( 'schedule_event', $event );
// A plugin disallowed this event.
if ( ! $event ) {
if ( $wp_error ) {
return new WP_Error(
'schedule_event_false',
__( 'A plugin disallowed this event.' )
);
}
return false;
}
$key = md5( serialize( $event->args ) );
$crons = _get_cron_array();
$crons[ $event->timestamp ][ $event->hook ][ $key ] = array(
'schedule' => $event->schedule,
'args' => $event->args,
'interval' => $event->interval,
);
uksort( $crons, 'strnatcasecmp' );
return _set_cron_array( $crons, $wp_error );
}
Hooks
- apply_filters( ‘pre_schedule_event’, null|bool|WP_Error $result, object $event, bool $wp_error )
-
Filter to override scheduling an event.
- apply_filters( ‘schedule_event’, object|false $event )
-
Modify an event before it is scheduled.
Changelog
| Version | Description |
|---|---|
| 5.7.0 | The $wp_error parameter was added. |
| 5.1.0 | Return value modified to boolean indicating success or failure, ‘pre_schedule_event’ filter added to short-circuit the function. |
| 2.1.0 | Introduced. |
Skip to note 8 content
Sushil Adhikari
Schedule hourly event with multiple arguments
wp_schedule_event() pass arguments by reference, so we have to send multiple data as indexed array.
register_activation_hook( __FILE__, 'my_activation' ); function my_activation() { $args = array( $args_1, $args_2 ); if (! wp_next_scheduled ( 'my_hourly_event', $args )) { wp_schedule_event( time(), 'hourly', 'my_hourly_event', $args ); } }Don’t forgot to add total number of argument as $accepted_args on add_action() .
add_action( 'my_hourly_event', 'do_this_hourly', 10, 2 ); function do_this_hourly($args_1, $args_2 ) { // do something every hour }Don’t forget to clean the scheduler on deactivation:
register_deactivation_hook( __FILE__, 'my_deactivation' ); function my_deactivation() { wp_clear_scheduled_hook( 'my_hourly_event' ); }wp_clear_scheduled_hook( 'my_hourly_event' );is missing the arguments. Fix:wp_clear_scheduled_hook( 'my_hourly_event', array($args_1, $args_2) );Skip to note 9 content
Codex
Schedule an hourly event
To schedule an hourly event in a plugin, call
wp_schedule_eventon activation (otherwise you will end up with a lot of scheduled events!):register_activation_hook( __FILE__, 'my_activation' ); add_action( 'my_hourly_event', 'do_this_hourly' ); function my_activation() { wp_schedule_event( time(), 'hourly', 'my_hourly_event' ); } function do_this_hourly() { // do something every hour }Don’t forget to clean the scheduler on deactivation:
register_deactivation_hook( __FILE__, 'my_deactivation' ); function my_deactivation() { wp_clear_scheduled_hook( 'my_hourly_event' ); }Skip to note 10 content
Sander van Dragt
An actual working best-practice minimal example.
function svd_deactivate() { wp_clear_scheduled_hook( 'svd_cron' ); } add_action('init', function() { add_action( 'svd_cron', 'svd_run_cron' ); register_deactivation_hook( __FILE__, 'svd_deactivate' ); if (! wp_next_scheduled ( 'svd_cron' )) { wp_schedule_event( time(), 'daily', 'svd_cron' ); } }); function svd_run_cron() { // do your stuff. }Skip to note 11 content
Chad Reitsma
It should be noted that depending on how resource-intensive your hook is, the default behavior of “Waiting until a user visits the site” may not be suitable. Of course you should try to make your code as efficient as possible – but if you have a specific case where it’s still resource intensive you do not want to keep the user sitting on a white screen while your hook does it’s work.
For specific situations you might want to consider disabling WP’s internal CRON by placing this line:
define('DISABLE_WP_CRON', 'true');into the file:
wp-config.phpThen create a CRON job with your hosting control panel to fetch the URL:
https://example.com/wp-cron.php?doing_wp_cron
OR execute:
/usr/bin/php -q /path-to-your-wp-installation/wp-cron.php
Your specific environment may vary.
Skip to note 12 content
Mário Valney
Note: If you are using custom recurrences make sure to call wp_schedule_event after you added the cron_schedules filter.
Skip to note 13 content
DVHOST_CLOUD
Per Minute.
add_filter( 'cron_schedules', function ( $schedules ) { $schedules['per_minute'] = array( 'interval' => 60, 'display' => __( 'One Minute' ) ); return $schedules; } );Skip to note 14 content
Codex
Usage