If i have the following entries in my cron table:
00 03 * * * /java_prog1.sh
00 5 * * * /java_prog2.sh
The first job usually takes around 30 m
Just putting some flesh on top of the suggestions already there in the comments.
Put in the beginning of java_prog1.sh
:
[ -f /var/run/java_prog1.sh.pid ] && exit
echo "$$" > /var/run/java_prog1.sh.pid
... everything else our script does ...
rm -f /var/run/java_prog1.sh.pid
Then in the beginning of java_prog2.sh
:
[ -f /var/run/java_prog1.sh.pid ] && exit
... the rest of your java_prog2.sh ...
Or:
if [ -f /var/run/java_prog1.sh.pid ]; then
kill -0 `cat /var/run/java_prog1.sh.pid` > /dev/null 2>&1 && exit
fi
... the rest of your java_prog2.sh ...
The first one will just exit immediately, if the a file (possibly and probably containing a PID from the first script) exists. The second one will exit only if the file exists and a process with a PID in in that file is in the process table (kill -0
will return 0 in case it does).
As far as the actual scripting goes, you probably have to experiment a bit. This is just to give you a rought idea how it might go.
Is there a way I can configure the two jobs so that the second job does not start if the first one is still running?
Since I can't comment, I will give you another example of what you could consider but of course @sami-laine solution is more elegant.
You can simply edit a config file like that:
echo 0 > file.config
echo 1 > file.config # at the beginning of the script
do something ...
echo 0 > file.config # at the end of script
#let the other script know that the job was finished
while [ `cat file.config` -eq 1 ] ; do sleep 5; done # Wait whatever want
The creation of directories is atomic, so you could add this in both scripts:
lock_dir=/tmp/name_of_lock_directory
if ! mkdir "$lock_dir"; then
echo "Cannot run $0: lock directory $lock_dir exists" >&2
exit 1
fi
cleanup () { rm -r "$lock_dir"; }
trap cleanup EXIT
# if you want, you can add the running pid to a file in the lock directory
echo $$ > "$lock_dir/pid"