As we all know cron job can be scheduled in linux systems. So scheduling the any job in wordpress is easy because scheduling the events in wordpress is provided by wordpress itself.
How to schedule events in wordpress
WordPress provides the following functions to schedule the events.
wp_schedule_event(); //using this method you can schedule events.
You can pass following parameters to this method.
wp_schedule_event(time(), ‘hourly’, ‘your_event’);
Following params you need to pass to this method.
$timestamp
(integer) (required) The first time that you want the event to occur. This must be in a UNIX timestamp format.
Default: None
$recurrance
(string) (required) How often the event should reoccur. Valid values:
* hourly
* twicedaily
* daily
Default: None
$hook
(string) (required) The name of an action hook to execute.
Default: None
$args
(array) (optional) Arguments to pass to the hook function(s).
Default: None
You can Schedule an hourly event. Example as follows:
register_activation_hook(__FILE__, ‘my_activation’);
add_action(‘my_hourly_event’, ‘do_this_hourly’);
function my_activation() {
wp_schedule_event(time(), ‘hourly’, ‘my_hourly_event’);
}
function do_this_hourly() {
// do something every hour
}
Don’t forget to clean the scheduler on deactivation:
register_deactivation_hook(__FILE__, ‘my_deactivation’);
function my_deactivation() {
wp_clear_scheduled_hook(‘my_hourly_event’);
}
Now I am going to tell you how to extend the wp_schedule_event().
We can add the more recurrences adding following code.
function ten_minute_reccurences() {
return array(
‘ten_minute_reccurences’ => array(‘interval’ => 60*10, ‘display’ => ‘Once in Ten Mintues’),
);
}
add_filter(‘cron_schedules’, ‘ten_minute_reccurences’);
If you want check this recurrences added to wp_schedule_event or not. You need to just use following code to print recurrences
php print_r(wp_get_schedules()); ?>
I found useful following URLs.
http://codex.wordpress.org/Function_Reference/wp_schedule_event
http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
http://codex.wordpress.org/Plugin_API
If you have PHP knowledge than you should open wp-includes/cron.php file. This file has best information and methods about scheduler.
I’m running the latest wp 3.2. When I try creating a schedule (just like you mentioned above), I get an “Illegal Offset” error in /wp-includes/cron.php on line 79. Since I didn’t edit the core cron.php file, I’m not sure what’s wrong. Here’s my code that calls the function:
$start_date = strtotime(’27 September 2011′);
wp_schedule_event($start_date, ‘hourly’, array(&$this, ‘do_cron’));
Additionally, in the same class is a function called do_cron, just so you’re sure.
Any ideas?
nice! thank you so much! Thank you for sharing. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.