Lockable CRON Jobs

Posted May 10, 2010

Where I work, we run loads of CRON jobs. For obvious reasons, it's the simplest way of executing regular processes. Since my place of work is almost exclusively a PHP shop, our CRON jobs are simply PHP CLI apps.

As you may expect, it is always a concern that a CRON jobs would try to run before the previous instance has completed - a rather precarious situation. To cater for this, I came up with a small BASH script which you can include (via the "source" instruction) into another BASH script which ultimately executes the PHP script.

Here is the locking source:

#!/bin/sh
test_lock() {
    # test if PID for this function
    if [ -e /var/run/$1.pid ]; then
        OLD_PID=`cat /var/run/$1.pid`

        #is it still alive?
        ACTIVE=`ps -p $OLD_PID --no-headers -o cmd`

        if [ "$ACTIVE" = "$2" ]; then
            echo "Job is still active"
            exit
        fi
    fi
}

run_lock() {
    $2 &
    NEW_PID=$!

    echo $NEW_PID > /var/run/$1.pid
}

Here is an example usage:

#!/bin/sh
source ./lockable.sh

NAME=MyPhpScript

test_lock $NAME "php $NAME.php"
cd jobs/rets
run_lock $NAME "php $NAME.php"

So what is happening here?

The "test_lock()" function takes in 2 parameter - the name of the PHP file (minus the ".php" file extension), and the command which was used to launch the target PHP script. Using the name, it looks for a ".pid" file. If it exists, it reads the file to get the PID for the last time the script was run. Using "ps", it then queries the OS to see if that PID is still active, and most importantly if it refers to the same command as supplied in parameter 2.

The "run_lock()" function takes in the same 2 parameters, runs the PHP script in the background - specifically so that it can get the PID and write it to the file.

That's it - short, sweet, and (thus far) fairly stable.

Comments

There are no comments for this post.

No comments found

Add comment

Visit my Friends and Family

If you've enjoyed my site, please take a moment to visit my friends and family, many of whom have some interesting insights, and entertaining thoughts and ideas.