Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 7527  / 2 Years ago, fri, december 3, 2021, 4:37:49

I have a Cron Job scripts which runs every 4 minutes.
In rare cases the script is not finished within 4 minutes.
This causes problems.



How can I perform a check that if there the previous script is not finished then skip the current run



Expected behavior:



10:00 : Script A starts
10:04 : Script A2 starts - it finds that script A was not finish so this script aborts. Simply finish without doing nothing.
10:06 : Script A finish
10:08 : Script A3 starts - no other scripts running so it continue


Notice: A, A2, A3 are the same script (just in different times)! It shouldn't consider other scripts that might be running also


More From » cron

 Answers
7

There are two main approaches:






  1. make the script exit if it detects another instance of itself running. Just add these lines to the beginning of your script:



    if [ $(pgrep -c "${0##*/}") -gt 1 ]; then
    echo "Another instance of the script is running. Aborting."
    exit
    fi


    $0 is the name of the script, and ${0##*/} is the name of the script with everything until the last / removed (so, /path/to/script.sh becomes script.sh). This means that if you have another, unrelated script with the same name running, it will still be detected. on the other hand, it also means that it will work even if you call the script from a symlink. Which one you prefer depends on your use case.


  2. Use a lock file and exit the script if the file exists:



    #!/bin/bash

    if [ -e "/tmp/i.am.running" ]; then
    echo "Another instance of the script is running. Aborting."
    exit
    fi
    else
    touch "/tmp/i.am.running"
    fi

    ## The rest of the script goes here

    rm "/tmp/i.am.running"


[#11247] Friday, December 3, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
fertion

Total Points: 436
Total Questions: 121
Total Answers: 156

Location: England
Member since Sun, May 21, 2023
1 Year ago
;