How to prevent duplicate cron jobs from running?

Better Stack Team
Updated on October 5, 2023

Sometimes you may find that duplicate cronjobs are running at the same time. This may happen when the cronjob takes longer to complete than its execution interval. Here is a simple way to prevent this from happening ever again.

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.

Use flock

Flock is a very simple and easy-to-use utility found in most Linux systems.

Its functionality goes like this. It takes two parameters - a lock file and a command (or shell script).

It locks the lock file at the start of the execution of the command and unlocks it at the end. Then if the same cronjob is started it checks if the lock file is still locked. If the lock file is locked, it means that the previous cronjob isn't finished yet and the flock will prevent from starting a new one.

 
*   *  *   *   *  /usr/bin/flock -n /home/myfolder/file.lockfile /bin/backup.sh

This will create a cronjob that runs the /bin/backup.sh script and prevent duplicate cronjobs from running using /home/myfolder/file.lockfile lock file.