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/

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

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github