I found a nice lock file system to ensure your PHP scripts run from cron don't overlap.

It works beautifully in my setup in which I have a script that is called four times each minute by cron, but it's possible that the script can run for more than 15 seconds, and if it does it will result in two copies of the script running at once, something I don't want.

Anyway, I thought about ways to implement a lock file system where the PHP script which is called from cron will check to see if a lock file exists, and if the lock file does exist, then the script will exit because the existence of a lock file would mean that a copy of the cron script is already running. 

But it turns out I didn't have to create a PHP lock file script because somebody already made one, and they did it in a way that is much better than I would have implemented one.

The PHP lock file script is explained very well at ABHI'S WEBLOG, and if you want to get a copy of the script, you can find it at his github repo.

Implementing the script couldn't be easier.

If the PHP script you want to run from a cron job is called myCron.php, then all you'd need to do to implement a lock file system this way is to wrap myCron.php in another file which includes the following PHP code:

 

<?php

require 'cronHelper/cron.helper.php';

if(($pid = cronHelper::lock()) !== FALSE) {

/*

* Cron job code goes here

*/

require('myCron.php');

cronHelper::unlock();

}

?>

 

Do you see how the myCron.php script is called with the require function? 

This wrapper script is what you'd call with cron. Calling the wrapper will allow your script to be run with the lock file feature which only allows one copy of your PHP program to be run at once. 

This script is working out really well for me. It's an alternative to what I was going to do, which was trying to run a PHP script as a daemon like this example I found.

Oh, and if you want to know how I'm running a PHP script from cron 4 times per minute, well all I'm doing is running my script 4 different times preceded by the sleep command set for varying durations. 

Like this:

php /path/to/my/script.php

sleep 15; php /path/to/my/script.php

sleep 30; php /path/to/my/script.php

sleep 45; php /path/to/my/script.php

 

That's all you really have to do. Each of those commands are run at 1 minute intervals, but with the sleep command, they are delayed so that they are spaced apart in 15 second intervals.