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
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