Run cron job only if it isn't already running

后端 未结 16 840
执笔经年
执笔经年 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:27

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

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

    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}"
    
    0 讨论(0)
  • 2020-11-29 15:29

    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.

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

    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
    
    0 讨论(0)
  • 2020-11-29 15:33

    You can also do it as a one-liner directly in your crontab:

    * * * * * [ `ps -ef|grep -v grep|grep <command>` -eq 0 ] && <command>
    
    0 讨论(0)
  • 2020-11-29 15:36

    The way I am doing it when I am running php scripts is:

    The crontab:

    * * * * * php /path/to/php/script.php &
    

    The php code:

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

    0 讨论(0)
提交回复
热议问题