Prevent cronjobs from overlapping in Linux

Recently while fixing a bug, I found out that there are multiple copies of same cronjob running at the same time. Normally, the task completes in just a few seconds. If the task takes longer than a minute, however, we end up with multiple copies running at once. This situation can make havoc in you app. Its better to introduce some kind of locking mechanism. flock(1) is the right tool for that.

*/1 * * * * /usr/bin/flock -n /tmp/cronjob.lockfile /usr/bin/php /var/www/some.php >> /root/cronjob.txt 

The -n option tells flock not to wait for the lock, but to exit. Simply this one liner made my life way easier.

About Zakir Hyder

This entry was written by .

14. August 2014 by Zakir Hyder
Categories: Linux | Tags: , , , | Comments

Comments

  1. […] Recently while fixing a bug, I found out that there are multiple copies of same cronjob running at the same time. Normally, the task completes in just a few seconds. If the task takes longer than a minute, however, we…  […]