I have one php script, and I am executing this script via cron every 10 minutes on CentOS.
The problem is that if the cron job will take more than 10 minutes, then another instance of the same cron job will start.
I tried one trick, that is:
- Created one lock file with php code (same like pid files) when
the cron job started. - Removed the lock file with php code when the job finished.
- And when any new cron job started execution of script, I checked if lock
file exists and if so, aborted the script.
But there can be one problem that, when the lock file is not deleted or removed by script because of any reason.
The cron will never start again.
Is there any way I can stop the execution of a cron job again if it is already running, with Linux commands or similar to this?
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.In this case I’m adding
LOCK_NBto 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.