Run cron job only if it isn't already running Run cron job only if it isn't already running linux linux

Run cron job only if it isn't already running


Use flock. It's new. It's better.

Now you don't have to write the code yourself. Check out more reasons here: https://serverfault.com/a/82863

/usr/bin/flock -n /tmp/my.lockfile /usr/local/bin/my_script


I do this for a print spooler program that I wrote, it's just a shell script:

#!/bin/shif ps -ef | grep -v grep | grep doctype.php ; then        exit 0else        /home/user/bin/doctype.php >> /home/user/bin/spooler.log &        #mailing program        /home/user/bin/simplemail.php "Print spooler was not running...  Restarted."         exit 0fi

It runs every two minutes and is quite effective. I have it email me with special information if for some reason the process is not running.


As others have stated, writing and checking a PID file is a good solution. Here's my bash implementation:

#!/bin/bashmkdir -p "$HOME/tmp"PIDFILE="$HOME/tmp/myprogram.pid"if [ -e "${PIDFILE}" ] && (ps -u $(whoami) -opid= |                           grep -P "^\s*$(cat ${PIDFILE})$" &> /dev/null); then  echo "Already running."  exit 99fi/path/to/myprogram > $HOME/tmp/myprogram.log &echo $! > "${PIDFILE}"chmod 644 "${PIDFILE}"