Run cron job only if it isn't already running

后端 未结 16 838
执笔经年
执笔经年 2020-11-29 14:53

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...

相关标签:
16条回答
  • 2020-11-29 15:16

    Don't try to do it via cron. Have cron run a script no matter what, and then have the script decide if the program is running and start it if necessary (note you can use Ruby or Python or your favorite scripting language to do this)

    0 讨论(0)
  • 2020-11-29 15:16

    With lockrun you don't need to write a wrapper script for your cron job. http://www.unixwiz.net/tools/lockrun.html

    0 讨论(0)
  • 2020-11-29 15:18

    Consider using pgrep (if available) rather than ps piped through grep if you're going to go that route. Though, personally, I've got a lot of mileage out of scripts of the form

    while(1){
      call script_that_must_run
      sleep 5
    }
    

    Though this can fail and cron jobs are often the best way for essential stuff. Just another alternative.

    0 讨论(0)
  • 2020-11-29 15:20

    This one never failed me:

    one.sh:

    LFILE=/tmp/one-`echo "$@" | md5sum | cut -d\  -f1`.pid
    if [ -e ${LFILE} ] && kill -0 `cat ${LFILE}`; then
       exit
    fi
    
    trap "rm -f ${LFILE}; exit" INT TERM EXIT
    echo $$ > ${LFILE}
    
    $@
    
    rm -f ${LFILE}
    

    cron job:

    * * * * * /path/to/one.sh <command>
    
    0 讨论(0)
  • 2020-11-29 15:22

    I would recommend to use an existing tool such as monit, it will monitor and auto restart processes. There is more information available here. It should be easily available in most distributions.

    0 讨论(0)
  • 2020-11-29 15:22
    # one instance only (works unless your cmd has 'grep' in it)
    ALREADY_RUNNING_EXIT_STATUS=0
    bn=`basename $0`
    proc=`ps -ef | grep -v grep | grep "$bn" | grep -v " $$ "`
    [ $? -eq 0 ] && {
        pid=`echo $proc | awk '{print $2}'`
        echo "$bn already running with pid $pid"
        exit $ALREADY_RUNNING_EXIT_STATUS
    }
    

    UPDATE .. better way using flock:

    /usr/bin/flock -n /tmp/your-app.lock /path/your-app args 
    
    0 讨论(0)
提交回复
热议问题