I\'m trying to set up a cron job as a sort of watchdog for a daemon that I\'ve created. If the daemon errors out and fails, I want the cron job to periodically restart it...
As a follow up to Earlz answer, you need a wrapper script that creates a $PID.running file when it starts, and delete when it ends. The wrapper script calls the script you wish to run. The wrapper is necessary in case the target script fails or errors out, the pid file gets deleted..
As others have stated, writing and checking a PID file is a good solution. Here's my bash implementation:
#!/bin/bash
mkdir -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 99
fi
/path/to/myprogram > $HOME/tmp/myprogram.log &
echo $! > "${PIDFILE}"
chmod 644 "${PIDFILE}"
I do this for a print spooler program that I wrote, it's just a shell script:
#!/bin/sh
if ps -ef | grep -v grep | grep doctype.php ; then
exit 0
else
/home/user/bin/doctype.php >> /home/user/bin/spooler.log &
#mailing program
/home/user/bin/simplemail.php "Print spooler was not running... Restarted."
exit 0
fi
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.
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
You can also do it as a one-liner directly in your crontab:
* * * * * [ `ps -ef|grep -v grep|grep <command>` -eq 0 ] && <command>
The way I am doing it when I am running php scripts is:
* * * * * php /path/to/php/script.php &
<?php
if (shell_exec('ps aux | grep ' . __FILE__ . ' | wc -l') > 1) {
exit('already running...');
}
// do stuff
This command is searching in the system process list for the current php filename if it exists the line counter (wc -l) will be greater then one because the search command itself containing the filename
so if you running php crons add the above code to the start of your php code and it will run only once.