Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...