
A cron job allows you to automatically set a function to run at a set time or interval. WordPress comes with an in-built function wp_schedule_event().
WordPress Schedule Event
The function wp_schedule_event() allows you schedule a hook to run an action to schedule a function to run at a set interval.
<?php wp_schedule_event($timestamp, $recurrence, $hook, $args); ?>Schedule An Hourly Event In Plugin
To schedule an hourly event within a plugin you will schedule a function on activation of the plugin.
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
// do something every hour
}
If you want to deactivate the schedule event then use this.
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
Schedule hourly Event In Functions.php
This doesn't rely on activation of the plugin as it will run inside the functions.php file.
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
function do_this_hourly() {
// do something every hour
}
