WordPress cron job mechanism

A function in cron.php wp_cron() is hooked to init action to check crons(got from the ‘cron’  option in the wp_options table).

if it sees there is a cron that should be done now(time arrived), it posts to the url wp-cron.php with the current time as the query parameter. wp-cron.php will check the ‘cron’ option again to see if there is a cron to be done now , if there is, will call wp_reschedule_event in cron.php first to reschedule the cron job. wp_reschedule_event calculates the timestamp of the next occurrence of this cron job and calls wp_schedule_event to schedule it at that time(i.e. change the timestamp field in the ‘cron’ option). wp-cron.php then calls wp_unschedule_event to delete that entry in the ‘cron’ option. The real job is called by do_action_ref_array(hook,…),which calls the functions hooked to the action(so you need to add_action elsewhere in the plugin).

the structure of crons:

$crons is an array with the timestamp(the time the cron job is to be executed) as the key and the cronhooks as the value.

$cronhooks is also an array with the hook name as the key and $args as the value.

$args is also an array with with a hash (calculate from the second parameter of the parameter array as the parameter array passed to the hooked function) as the key and parameter array as the value.

Do not be confused with $schedules and $crons. Most of the information needed to set up crons are stored in $crons, $schedules is just for storing the information of intervals such as “hourly”,”daily”, etc.

To set up a cron job, first we should create an action and hook our cron function into that action. Then we call wp_schedule_event(timestamp, "daily", "actionname") to let that action done daily(the first execution will be at timestamp). We can set up our cron job to be done hourly, twice daily, and daily, but if we want other schedule intervals, we should add a filter as

function get_myown_schedule($schedules)
  return $schedules;

so that we can use “weekly” in the wp_schedule_event function.

If you find your cron job not working, it is not necessarily a problem. WordPress cron job can only be done when someone visits your website. To check if your cron job is running, just visit your website and see the results. To avoid cron job missing, you can set up a linux cron job to access your website in a fixed interval.

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply