PHP超时(暂停时间)在一个循环 [英] php timeout (pause time) in a loop

查看:360
本文介绍了PHP超时(暂停时间)在一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在php中暂停循环,例如,它每5分钟执行一次

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
}

简单的例子

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
}

推荐答案

此脚本可以按预期工作.循环的每次迭代都会延迟5秒.但是,您看到的是发送到浏览器的输出,该输出在特定时间(通常在脚本执行完成时)由PHP缓冲和传递.

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).

您可以尝试使用ob_get_contents()来在每次迭代中检索输出缓冲区.

You can try playing with ob_get_contents() to retrieve the output buffer on each iteration.

PHP手册: ob_get_contents()

请注意,使用此方法可能会大大超出max_execution_time.长期的工作肯定是前进的方向.或者,您可以让浏览器保持打开状态,并每5分钟强制刷新一次(不实际).

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).

这篇关于PHP超时(暂停时间)在一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆