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...
I'd suggest the following as an improvement to rsanden's answer (I'd post as a comment, but don't have enough reputation...):
#!/usr/bin/env bash
PIDFILE="$HOME/tmp/myprogram.pid"
if [ -e "${PIDFILE}" ] && (ps -p $(cat ${PIDFILE}) > /dev/null); then
echo "Already running."
exit 99
fi
/path/to/myprogram
This avoids possible false matches (and the overhead of grepping), and it suppresses output and relies only on exit status of ps.
Docs: https://www.timkay.com/solo/
solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.
Example
* * * * * solo -port=3801 ./job.pl blah blah
It's suprising that no one mentioned about run-one. I've solved my problem with this.
apt-get install run-one
then add run-one
before your crontab script
*/20 * * * * * run-one python /script/to/run/awesome.py
Check out this askubuntu SE answer. You can find link to a detailed information there as well.
Simple custom php is enough to achieve. No need to confuse with shell script.
lets assume you want to run php /home/mypath/example.php if not running
Then use following custom php script to do the same job.
create following /home/mypath/forever.php
<?php
$cmd = $argv[1];
$grep = "ps -ef | grep '".$cmd."'";
exec($grep,$out);
if(count($out)<5){
$cmd .= ' > /dev/null 2>/dev/null &';
exec($cmd,$out);
print_r($out);
}
?>
Then in your cron add following
* * * * * php /home/mypath/forever.php 'php /home/mypath/example.php'