But what to do if you need to execute your task more often, than default schedule intervals offered by WordPress? Can you manage WordPress scheduler to start your job every 5 minutes instead of ‘hourly’, ‘twicedaily’ and ‘daily’ intervals?
Yes. I found the answer inside wp_schedule_event()
function source code. It is well commented:
"Valid values for the recurrence are hourly, daily and twicedaily. These can be extended using the cron_schedules filter in wp_get_schedules()".
So we can configure any custom time interval for WP Cron task schedule. Look how it could be done:
add_filter('cron_schedules', 'add_scheduled_interval'); // add once 5 minute interval to wp schedules public function add_scheduled_interval($schedules) { $schedules['minutes_5'] = array('interval'=>300, 'display'=>'Once 5 minutes'); return $schedules; } |
We just added new ‘minutes_5’ interval (300 seconds = 60 * 5 = 5 minutes) to the list of WP Cron schedule intervals and can use it to schedule new WP Cron job.
Let’s do the final step – setup our cron job to be executed every 5 minutes:
if (!wp_next_scheduled('your_cron_hook_name_here')) { wp_schedule_event(time(), 'minutes_5', 'your_cron_hook_name_here'); } add_action('your_cron_hook_name_here', 'your_task_executor'); function your_task_executor() { // some code to execute by schedule here } |
For additional reading I offer you to pay attention of these very useful tutorials related to WP Cron:
- Do it yourself. WordPress Scheduling: Mastering WP Cron.
- Insights into WP Cron. An introduction to scheduling tasks in WordPress
- WP Cron API at WordPress Codex
Tags: WordPress