In this tutorial I will provide a method to run cron jobs in PHP that too asynchronous without affecting page load time. This doesn’t require to install any PHP extension or any other kinds of coding horrors.
Logic
We need two PHP files. The first file checks if scheduled time has passed or just occurred for a cron job. If its time to run the task then it starts a new asynchronous process to run the second PHP which is actually the cron callback.
Complete Code
Files are named: cron.php and schedule.php. cron.php contains the callback code and schedule.php should be runned every time user makes a request to the web server.
Here is the code for schedule.php
if(get_option("cron_job_1") != null)
{
//run task every 1 hour.
if(time() - get_option("cron_job_1") >= 3600)
{
$ch = curl_init();
//send a request to the cron.php file so that its started in a new process asynchronous to the current process.
curl_setopt($ch, CURLOPT_URL, 'http://yourdomain/cron.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
//close connection after 1 millisecond. So that we can continue current script exection without effect page load time.
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
//some versions of curl don't support CURLOPT_TIMEOUT_MS so we have CURLOPT_TIMEOUT for them. Here we close connection after 1 second.
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
curl_close($ch);
update_option("cron_job_1", time());
}
}
else
{
update_option("cron_job_1", time());
}
We have used PHP Options to store the last time in seconds when task was executed.
Here is the code for cron.php
// Ignore user aborts
ignore_user_abort(true);
//allow the script to run forever. this is optional depending on how heavy is the task
set_time_limit(0);
//put the task code here.