问题
I'm trying to figure out how to pause a loop in php so it executes once every 5 minutes for example
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
//send email to a member
// pause for a minute then continue the loop
}
simple example
for($x=0;$x<=4;$x++){
echo $x."<br>";
sleep(5);
// the loop will be delayed for 25 seconds then it'll print 5 lines at once
}
回答1:
This script works as you expect. Every iteration of the loop is being delayed 5 seconds. However, what you are seeing is the output sent to the browser, which is buffered and delivered by PHP at certain times (normally when the script execution finishes).
You can try playing with ob_get_contents()
to retrieve the output buffer on each iteration.
PHP Manual: ob_get_contents()
Please note that you may well exceed the max_execution_time
with this approach. A cron job is definitely the way forward. Or you can leave the browser open and force a refresh every 5 minutes (not practical).
来源:https://stackoverflow.com/questions/34138306/php-timeout-pause-time-in-a-loop