php循环中使用sleep就卡死,PHP sleep()内部循环不更新DB

I have a php file that is fired by a cronjob every minute.

我有一个php文件,它每分钟被一个cronjob触发。

When the php file is fired it updates the database, sleeps, etc

当启动php文件时,它更新数据库、休眠等

It is programmed like this:

它的程序是这样的:

$start = microtime(true);

set_time_limit(10);

for($i=0;$i<5;$i++)

{

updateDB();

time_sleep_until($start + $i + 1);

}

If this piece of code is run i don't see any changes happening in the database. Another thing i notices is when i echo something out i is printed when the loop is ended in one piece.

如果运行这段代码,我在数据库中看不到任何更改。我注意到的另一件事是当我回显一些东西时,当循环结束时,我被打印出来。

[edit] I tried using flush and ob_flush, but it still didn't print line for line[/edit]

[编辑]我尝试过使用flush和ob_flush,但它仍然没有为line[/edit]打印行

What can i do to avoid these errors. The database needs to be updated.

我能做些什么来避免这些错误。需要更新数据库。

Another thing i was wondering is what the best way is to log this kind of thing. Can i log the results to a log file.

我想知道的另一件事是最好的记录方式是什么。我可以将结果记录到日志文件中吗?

2 个解决方案

#1

4

The loop itself looks fine. If it isn't updating your database, the error must be in your updateDB() function.

循环本身看起来很好。如果它没有更新数据库,那么错误必须出现在updateDB()函数中。

As to the echo thing. The output of scripts is often buffered. To force PHP to print it right away, you can call either call flush() whenever you want the output flushed, or you can just call ob_implicit_flush() at the top of the script and it will flush automatically every time you print something.

至于回声。脚本的输出通常被缓冲。要强制PHP立即打印它,您可以在需要刷新输出时调用flush(),也可以在脚本顶部调用ob_implicit_flush(),每次打印内容时它将自动刷新。

Also, if you are calling the script via a browser, the browser itself may further buffer the response before showing it to you.

此外,如果您正在通过浏览器调用脚本,浏览器本身可以在向您显示响应之前进一步缓冲响应。

And as to the logging, the simplest way is to pick a file somewhere and just use file_put_contents() to print whatever you want logged. Note the FILE_APPEND flag for the third parameter.

至于日志记录,最简单的方法是在某个地方选择一个文件,然后使用file_put_contents()打印您想要记录的任何内容。注意第三个参数的FILE_APPEND标志。

#2

0

Looks like you are running from command line, in this case you may want to write to stderr so that there is no buffering. $stderr = fopen('php://stderr', 'w');

看起来您正在从命令行运行,在这种情况下,您可能想要写入stderr,这样就没有缓冲了。$ stderr = fopen(php:/ / stderr,' w ');

In the case of logging, just open a file, write to it, and close it. (fopen, fwrite, fclose);

在日志记录的情况下,只需打开一个文件,写入它,然后关闭它。(fopen写入文件,文件关闭);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值