How to prevent the cron job execution, if it is already running

Advisory locking is made for exactly this purpose.

You can accomplish advisory locking with flock(). Simply apply the function to a previously opened lock file to determine if another script has a lock on it.

$f = fopen('lock', 'w') or die ('Cannot create lock file');
if (flock($f, LOCK_EX | LOCK_NB)) {
    // yay
}

In this case I’m adding LOCK_NB to prevent the next script from waiting until the first has finished. Since you’re using cron there will always be a next script.

If the current script prematurely terminates, any file locks will get released by the OS.

Leave a Comment

tech