Search This Blog

2011-02-21

Cron Overlap Locking

It overlaps and starts running a new instance of the script you wanted to execute making a big mess and unpredictable results.

Here's how to fix that issue with cron job locking:

Step 1: Download and Install Steve Friedl's lockrun utility
From a sudoers terminal prompt issue the following command to download the utilitywget http://www.unixwiz.net/tools/lockrun.c
This utility basically does all the hard work of creating and checking lockfiles when you're running cronjobs. All you need to do is specify the lockfile and the script.

Step 3: Move this program to a better placesudo cp lockrun /usr/local/bin

Step 4: Using lockrun in crontab entriessudo nano /etc/crontab

Make a manual entry to the crontab (Mine is set to run every 5 minutes on the 5's)*/5 * * * * root /usr/local/bin/lockrun --lockfile=/var/run/mp4.lockrun -- /usr/local/bin/./mp4

I have set the script for my root user to run a script called mp4 in the /usr/local/bin directory every 5 minutesThe lockrun utility is run before this with the modifiers telling it where to store the lockfile it will use to check if the script is running as well as the script that is tied to the lockfile

As an important side note on the lockrun website:
Be sure to place the lockfile in a directory that only that user has the rights to, and not in /tmp (as this Tech Tip has previously suggested). If a different user has the ability to write to the directory, s/he could create a symbolic link from the target lockfile to some system file that uses locks the same way, and get the cron job to foul up the locking.