Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

PHP: How to use cron (or another method) to get a PHP script to run every second?

If I have a cron job that runs every minute, and the first iterations runs for 62 seconds, will the second iteration wait to start until the first occurance ends, or can it happen that the same cron job runs concurrently?

To illustrate this, see scenario 1:

|0    |60   |120  |180  |240  |300
------ Cron Job 1 Taking 60 Seconds
      --------- Cron Job 2 Taking 90 Seconds
            ------ Cron Job 3 Taking 90 Seconds but overlapping with the previous cron job

Is the above what will happen, or will scenario 2 happen:

|0    |60   |120  |180  |240  |300
------ Cron Job 1 Taking 60 Seconds
      --------- Cron Job 2 Taking 90 Seconds
               XXX-------Cron Job 3 waiting til the next 1 minute interval starts

My concern is that there will be a period for 30 seconds marked XXX where there will be NO cron job running.

What am I trying to accomplish? I want to execute a PHP script every single second, indefinitely. It doesn't have to run once a second, but it must RUN, END, RUN, END, RUN, END. If an iteration takes 5 seconds, it must only start the next one after the first has ended. But it must never ever stop. The problem is that I can't determine the length of an iteration. One iteration could take 1 second, or it could take 5 seconds, or even longer.

  1. Can cron do this? So that I can be guarenteed that the script will run every single second no matter what?
  2. If not, how can I gaurentee that a PHP script runs indefinitely, one iteration after the other?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can implement a simple locking mechanism as follow.

if(!locked()) {
    lock();
    // your code here
    unlock();
} else {
    echo "script already running";
}

function lock()   { file_put_contents("write.lock", 'running'); }
function locked() { return file_exists("write.lock"); }
function unlock() { return unlink("write.lock"); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...