Schedule cron jobs with WordPress

A cron job let’s you run a bit of code at a specific interval, for example you could have a script that empty the trash can every hour. However, to set up a cron job isn’t something you do on your lunch break. Luckily, WordPress can do this for you with the wp_schedule_event() function.

From the codex:

Schedules a hook which will be executed by the WordPress actions core on a specific interval, specified by you. The action will trigger when someone visits your WordPress site, if the scheduled time has passed.

Code Snippet:

<?php
add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
	if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
		wp_schedule_event(time(), 'hourly', 'my_hourly_event');
	}
}
add_action('wp', 'my_activation');

function do_this_hourly() {
	// do something every hour
}
?>

Posted in Pure hacks