Linux – Minutely cron, ensuring only a single instance

cronlinux

Is there a way to run a script every minute (or 2, or 5, etc), but only if it isn't already running?

We have a set of scripts that need to run every minute. Sometimes they might start and finish in a second, other times they might go on for 5 minutes.

Our current way of avoiding simultaneous executions is by setting a is_running flag in each script, and exiting if it's still enabled. But this is a little unreliable (i.e., fatal errors would cause the flag to remain enabled even after the script halted).

We could write our own little manager, but I'm wondering if there is a more fashionable solution that already exists.

Best Answer

a better way is to use flock instead of a pidfile. check the manpage: flock(1). The advantage is that no matter how a process finishes/dies, the lock is gone with it.