WordPress Cron Jobs are a great way to schedule events which occur at specific interval of time.
WordPress cron jobs run when current time is equal or more than the scheduled time of the cron job. WordPress makes this check whenever a HTTP request is sent to WordPress. If the scheduled time has occurred then WordPress runs the event during that HTTP request. But the best thing is that execution of cron jobs don’t effect the page load time. Although they are started during HTTP requests but they actually runs asynchronous to the HTTP request.
How does WordPress run Cron Jobs Asynchronously
There are basically two ways in PHP to run code asynchronous to the HTTP request execution
- You can use PHP program execution functions to run a new process parallel to the current HTTP request executing process. The new process will execute the scheduled event. But the problem with this method is that many shared hosting servers don’t support these PHP functions.
- You can send a HTTP request to a different PHP page in the same server which is responsible for running the scheduled event. This solution is better because every hosting server supports CURL library and file_get_contents function.
WordPress uses the second method. When WordPress needs to run a cron event it simply makes a HTTP request to wp-cron.php file passing the cron job name. WordPress doesn’t wait for the HTTP request to finish i.e., the HTTP request is made asynchronous to the current page execution. Therefore there is no way it would effect page load time.
Example
WordPress uses WordPress HTTP API to make a request to the wp-cron.php file.
//blocking indicates weather we want to allow PHP to continue execution while the transport is working. Setting it to false makes the request happen in background and therefore it doesn't effect current page load time. Internally true value uses synchronous sockets and false value uses asynchronous sockets.
$args = array(
"method" => "GET",
"timeout" => 100,
"blocking" => false
);
wp_remote_request("http://domain.name/wp-cron.php?job=backup", $args);
Leave a Reply