Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent the cron job execution, if it is already running

Tags:

php

cron

centos

I have one php script, and I am executing this script via cron every 10 minutes on CentOS.

The problem is that if the cron job will take more than 10 minutes, then another instance of the same cron job will start.

I tried one trick, that is:

  1. Created one lock file with php code (same like pid files) when the cron job started.
  2. Removed the lock file with php code when the job finished.
  3. And when any new cron job started execution of script, I checked if lock file exists and if so, aborted the script.

But there can be one problem that, when the lock file is not deleted or removed by script because of any reason. The cron will never start again.

Is there any way I can stop the execution of a cron job again if it is already running, with Linux commands or similar to this?

like image 622
Sanjay Avatar asked May 11 '12 13:05

Sanjay


People also ask

How do I stop a cron job execution?

You can stop a single cron job by removing its line from the crontab file. To do that, run the crontab -e command and then delete the line for the specific task. Alternatively, you can stop the cron job by commenting it out in the crontab file.

What is the use of * * * * * In cron?

It is a wildcard for every part of the cron schedule expression. So * * * * * means every minute of every hour of every day of every month and every day of the week .


2 Answers

Advisory locking is made for exactly this purpose.

You can accomplish advisory locking with flock(). Simply apply the function to a previously opened lock file to determine if another script has a lock on it.

$f = fopen('lock', 'w') or die ('Cannot create lock file'); if (flock($f, LOCK_EX | LOCK_NB)) {     // yay } 

In this case I'm adding LOCK_NB to prevent the next script from waiting until the first has finished. Since you're using cron there will always be a next script.

If the current script prematurely terminates, any file locks will get released by the OS.

like image 86
Ja͢ck Avatar answered Oct 02 '22 16:10

Ja͢ck


Maybe it is better to not write code if you can configure it:

https://serverfault.com/questions/82857/prevent-duplicate-cron-jobs-running

like image 20
Leonid Shagabutdinov Avatar answered Oct 02 '22 14:10

Leonid Shagabutdinov