Preventing to Bash script from running in parallel or overlap using cron

后端 未结 3 1677
谎友^
谎友^ 2021-01-28 15:27

If i have the following entries in my cron table:

00 03 * * * /java_prog1.sh 
00 5 * * * /java_prog2.sh

The first job usually takes around 30 m

3条回答
  •  生来不讨喜
    2021-01-28 15:50

    Just putting some flesh on top of the suggestions already there in the comments.

    Put in the beginning of java_prog1.sh:

    [ -f /var/run/java_prog1.sh.pid ] && exit
    echo "$$" > /var/run/java_prog1.sh.pid
    
    ... everything else our script does ...
    
    rm -f /var/run/java_prog1.sh.pid
    

    Then in the beginning of java_prog2.sh:

    [ -f /var/run/java_prog1.sh.pid ] && exit
    
    ... the rest of your java_prog2.sh ...
    

    Or:

    if [ -f /var/run/java_prog1.sh.pid ]; then
       kill -0 `cat /var/run/java_prog1.sh.pid` > /dev/null 2>&1 && exit
    fi
    
    
    ... the rest of your java_prog2.sh ...
    

    The first one will just exit immediately, if the a file (possibly and probably containing a PID from the first script) exists. The second one will exit only if the file exists and a process with a PID in in that file is in the process table (kill -0 will return 0 in case it does).

    As far as the actual scripting goes, you probably have to experiment a bit. This is just to give you a rought idea how it might go.

提交回复
热议问题