Using flock to ensure only one instance of script is running

When you have a cron job that takes a while to finish, you need to be sure the next scheduled execution won’t come before completion of previous one. (For example you want file backup to finish before starting a new one).
Linux has one useful utility, that addresses this specific issue – flock.
[code]
/usr/bin/flock -w 600 /var/tmp/myscript.lock /root/myscript.sh
[/code]
This will execute /root/myscript.sh only if previous instance of this script has finished.
Key -w 600 means that flock will wait for 10 minutes for previous instance of the script to finish, before aborting the execution.
You may want to put 0 here or omit the -w key entirely, so the script wait for indefinitely long time for previous instance to finish.

A bit better place for lock files is /var/run folder, however you may have to create a lockfile and give user write permissions for it before.

Leave a Reply

Your email address will not be published. Required fields are marked *