Simple WordPress Cron Plugin Tutorial

June 28, 2011

This is a very simple example of how to register a cron hook upon activation of a plug-in, and subsequently add a function action to that hook. I needed this for a plug-in I was developing, and find that although the pseudo-cron in WordPress is limited, it’s very useful for simple tasks.

<?php
// Upon activation or deactivation of the plugin run the appropriate functions.
// Note that __FILE__ just means the current file, also very important, do not put
// your activation and deactivation functions in a separate file which you include.
// This won't work, because of the file loading done in register activate and deactivate.
// If you have to, define two dummy functions in this main PHP file and call functions
// in the other included file. 
register_activation_hook(__FILE__, 'my_plugin_activation');
register_deactivation_hook(__FILE__, 'my_plugin_deactivation');
 
// We can assume that at this point, the cron hook is registered, and we can add a 
// function action to the execution of its hook.
add_action('my_hourly_cron', 'do_my_hourly_cron');
 
function my_plugin_activation () {
	// If our cron hook doesn't yet exist, create it.
	if (!wp_next_scheduled('my_hourly_cron')) {		
		wp_schedule_event( time(), 'hourly', 'my_hourly_cron');
	}
}
 
function my_plugin_deactivation () {
	// If our cron hook exists. remove it.
	if (wp_next_scheduled('my_hourly_cron')) {
		wp_clear_scheduled_hook('my_hourly_cron');
	}
}
 
function do_my_hourly_cron () {
	// Do cron tasks here.
	// 1 minute maximum, keep that in mind.
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*