Search This Blog


Cron Overlap Locking

  • Lets say you have a cron job set to run every hour.
  • Lets assume this job takes longer than an hour to actually complete.
  • What happens when that initial cron job runs again?
  • 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 utility
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 2: Build this C program using gcc compiler
gcc lockrun.c -o lockrun

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

Step 4: Using lockrun in crontab entries
sudo 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 minutes
The 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.

Note: If you have any issues with the lockrun program please visit the originating website for this tool

For more information on creating crontabs for different repetition periods see the following:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.