wp_get_scheduled_event()
Retrieve a scheduled event.
Retrieves the full event object for a given event, if no timestamp is specified the next scheduled event is returned.
Uses: _get_cron_array()
Return
Object|false
. The event object. False if the event does not exist.
Usage
wp_get_scheduled_event( $hook, $args, $timestamp );
- $hook(string) (required)
- Action hook of the event.
- $args(array)
- Array containing each separate argument to pass to the hook's callback function. Although not passed to a callback, these arguments are used to uniquely identify the event, so they should be the same as those used when originally scheduling the event.
Default: empty array - $timestamp(int|null)
- Unix timestamp (UTC) of the event. If not specified, the next scheduled event is returned.
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. |