wp_get_scheduled_event()
Gets the scheduled wp-cron task - the data of the specified task in the form of an object.
Uses: _get_cron_array()
Used By: wp_next_scheduled()
Hooks from the function
Returns
Object|false. Event object. False if the event does not exist.
Usage
wp_get_scheduled_event( $hook, $args, $timestamp );
- $hook(string) (required)
- Task name - WP hook that will be executed.
- $args(array)
- Parameters that were specified when registering the event in the function wp_schedule_event(). They are needed to accurately understand which task you want to retrieve - for unambiguous identification of the task.
Default: array() - $timestamp(int|null)
Event timestamp in Unix (UTC).
If this parameter is specified, the task with the specified timestamp will be retrieved.
If not specified, the next scheduled task for the event specified in $hook will be retrieved.
Default: null
Examples
#1 Event registering with cron schedule compliance checking.
The first time the code is run, it registers a cron task.
When restarting, it checks whether the trigger interval of the registered event corresponds to the time interval in the original array. If the triggering interval in the array has changed, the code reregisters the event with the new interval.
$events = [ 'my_event_name' => 'min' ];
foreach ( $events as $event_hook => $event_time ) {
// get a cron task
$cron_event = wp_get_scheduled_event( $event_hook );
// check that the task is not scheduled or has a different interval
if (
( false === $cron_event && '' !== $event_hook )
||
( is_object($cron_event) && $cron_event->schedule !== $event_time )
) {
// delete all the same cron tasks, just in case, to add new ones from a "clean slate"
wp_clear_scheduled_hook( $event_hook );
// add a new cron task
wp_schedule_event( time(), $event_time, $event_hook );
}
}
Checking the script above, an example of a returned object
$event_hook = 'my_event_name'; $result = wp_get_scheduled_event( $event_hook ); print_r( $result );
Result:
stdClass Object ( [hook] => my_event_name [timestamp] => 1636884508 [schedule] => min [args] => Array ( ) [interval] => 60 )
#2 Remove no-needed event
if ( false !== wp_get_scheduled_event( 'old_hook' ) ) {
wp_clear_scheduled_hook( 'old_hook' );
}
Changelog
| Since 5.1.0 | Introduced. |