The code below is my solution for preventing a program from running more than once at the same time in Linux.
The scenario: Consider if you have a cron job (jobA.sh) set to run at 6PM, 7PM, and 8PM.
While the 1st instance of jobA.sh started, it might (or might not) need more than an hour to finish. If it does requires more than one hour, while the 1st instance is still running, a 2nd instance of jobA.sh started.
Now you ended up with two instances of a same program consuming your CPU, files, etc – which will slow things down even more.
So here how I solve it:
When the 1st instance is started, check if there is a temporary lock file, if yes then just exits or quit. If not create the temporary lock file. And do your code/algorithm. After it finishes delete this lock file. When the 2nd instance started it will also do the same thing, checking if there is lock file.
It will be wise to put another cron job that cleans all lock file every 00:00AM. Just to be sure the next execution (at 6PM tomorrow) will be able to run
Since I’m no bash expert, let me know if there is a better way to do this. Cheers!
# author: Ronald Pringadi
# sleep command is in seconds
# If lockfile does not exist do the followings
if [ ! -f $vLockFile ]; then
echo "Lock file doesn't exists, executing code"
sleep 7 # this can be your big process that takes longer than an hour, but just for proof of concept, I use 7 seconds
echo "Lock file exists do nothing"