You need a cron job in your WordPress blog – something run to a schedule, hourly, daily… Instead of fixing up a crontab and using wget or lynx, you can use WordPress’s internal version of the cron job.
This isn’t a true cron job, with a crontab text file sitting on the server – it’s known as a pseudo-cron. Since a script can’t launch itself, it makes use of a visitor, human or maybe robot, launching it by requesting a page. So the job actually runs at the first launch after the scheduled time, not necessarily at the scheduled time to the exact second.
wp_schedule_event()
The most convenient way of using WP-Cron is to wrap it all up in a plugin – so that the scheduling can be done just the once by including it in the plugin activation function.
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_activation() {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
function do_this_hourly() {
// do something here every hour
}
The PHP time() used as an argument indicates “as of now” – so if the plugin is activated at 11:23, an hourly event is going to run at xx:23 from now onwards.
If your code is in for example functions.php and is executed every time the script is executed, you don’t want to keep scheduling the same event. Something like this prevents the problem:-
if (empty(wp_next_scheduled('my_event')))
wp_schedule_event(time(), 'daily', 'my_event');
WP-Cron Hourly, Recurrence Intervals
Only hourly, daily and twicedaily are available immediately – but there’s a trick to getting more and that’s to tap into the cron_schedules filter and add a key to the schedules array.
add_filter('cron_schedules', 'my_add_weekly');
function my_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('Once Weekly')
);
return $schedules;
}
