LorenVS LorenVS - 4 months ago 16x
Linux Question

Run cron job only if it isn't already running

So 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'm not sure how possible this is, but I read through a couple of cron tutorials and couldn't find anything that would do what I'm looking for...

My daemon gets started from a shell script, so I'm really just looking for a way to run a cron job ONLY if the previous run of that job isn't still running.

I found this post, which did provide a solution for what I'm trying to do using lock files, not I'm not sure if there is a better way to do it...

Thanks for your help.


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

if ps -ef | grep -v grep | grep doctype.php ; then
        exit 0
        /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

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.