As an employee of Feedster, Inc. It's important, while reading anything that I happen to blog,
that my entries here are solely my own opinion. Nothing that I say here even remotely reflects
anything about my employer. I am an individual, I have a job just as most everyone has a job. You
are reading the depraved ramblings of the individual not the employee. If you
read something that I say here and then go ranting about how Feedster feels regarding a subject
you will only be showing off your own narrow-minded-ignorance. Thanks for understanding.


Thursday, January 26, 2006

A locking cron job?! In bash?! You're joking right??

Because its one of those things that people often times need to do, and because usually people are at a complete loss as to HOW to accomplish this feat, here's a very simple template which you can use to add locking to a cron job (or any script, really).

It's got a decent feature set for the code-size: A) custom lock file, B) lock expiration, C) decent log type output, D) easily used to wrap another script, or set of scripts inside


#!/bin/bash

###
### Simple bash script locking illustration
###
### By: Demitrious S. Kelly
###
### FWIW: YMMV: Use at your own risk
###

LOCKFILE=/var/lib/locks/this_job.lock
LOCKEXPIRE=600
NOW=$(date +%s)
CONT=1

if [ -f $LOCKFILE ]
then
echo -e $(date)"\tLock Found"
CONT=0
LOCKTIME=$(cat $LOCKFILE)
let LOCKELAPSED=$NOW-$LOCKTIME
if [ $LOCKELAPSED -gt $LOCKEXPIRE ]
then
CONT=1
echo -e $(date)"\tLock Expired ($LOCKELAPSED), Contnuing"
else
echo -e $(date)"\tLock Not Yet Expired ($LOCKELAPSED), Aborting"
fi
else
echo -e $(date)"\tLock Not Found"
fi

if [ $CONT -eq 0 ]
then
exit 1
fi

echo -e $(date)"\tCreating Lockfile"
echo $NOW > $LOCKFILE

###
### Job goes below here, inside the lockfile wrapper
###

echo $(date +%s) > $LOCKFILE
## do stuff
## ...
echo $(date +%s) > $LOCKFILE
## do stuff
## ...
echo $(date +%s) > $LOCKFILE
## do stuff
## ...

###
### Job goes above here, inside the lockfile wrapper
###

echo -e $(date)"\tRemoving Lockfile\r\n\r\n"
rm $LOCKFILE

0 Comments:

Post a Comment

<< Home