Prevent CRON from overlapping

To solve situations where CRON starts another copy before the current one finishes.

At the top of the CRON job use:

//check if already running
$buff = file_get_contents("cron_stat.txt");
if($buff == 1)
{
    die();
}
//set a running flag;
file_put_contents("cron_stat.txt","1");
......
......
......

When the CRON will run for the first time “cron_stat.txt” will be blank so a 1 will be written in “cron_stat.txt” indicating that the CRON is running and the script will proceed with its work.
When the CRON will start again (second time onwards) it will check “cron_stat.txt” and if it finds there is a 1 in it the script it will exit. And if it finds a 0 then it will proceed.

At the end of the file use:

file_put_contents("cron_stat.txt","0");

This will write a 0 in the “cron_stat.txt” file indicating the CRON is not running.

So in short at the start of the script set 1 in a flag indicating the CRON is running and at the end of the script set the flag to 0 indicating CRON has finished.

There are ways to implement this through Linux commands, but didn’t work for me.

Leave a Reply