How to prevent duplicate cron jobs from running?

Better Stack Team
Updated on May 4, 2022

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.

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
Copied!

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.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack