Locking cron jobs

I was working with a developer this week who was struggling with what seemed to be a simple problem. He wanted a run a cron job every X minutes. However, sometimes the cron job would run long. Resulting in the job running in parallel. After some Google-fu I suggested using the utility flock.

flock places a lock on cronjob.lockfile while the ping is running. -n tells any other process trying to place a lock on cronjob.lockfile to fail immediately. You can test this by opening up another terminal sessions and firing off another ping The second process launched using flock should fail immediately.

flock -n /tmp/cronjob.lockfile -c ping

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s