PHP sleep() 内部循环不更新数据库
我有一个 php 文件,每分钟由 cronjob 触发一次。
当 php 文件被触发时,它会更新数据库、睡眠等。
它的编程如下:
$start = microtime(true);
set_time_limit(10);
for($i=0;$i<5;$i++)
{
updateDB();
time_sleep_until($start + $i + 1);
}
如果运行这段代码,我看不到数据库中发生任何更改。我注意到的另一件事是,当我回显某些内容时,当循环完整结束时,我会被打印出来。
[编辑]我尝试使用flush和ob_flush,但它仍然没有逐行打印[/编辑]
我能做些什么来避免这些错误。数据库需要更新。
我想知道的另一件事是记录此类事情的最佳方法是什么。我可以将结果记录到日志文件中吗?
I have a php file that is fired by a cronjob every minute.
When the php file is fired it updates the database, sleeps, etc
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]
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
循环本身看起来不错。如果它没有更新您的数据库,则错误一定出在您的 updateDB() 函数中。
至于回声的事。脚本的输出通常会被缓冲。要强制 PHP 立即打印它,您可以在需要刷新输出时调用 flush() ,或者您可以在脚本顶部调用 ob_implicit_flush() ,每次打印内容时它都会自动刷新。
此外,如果您通过浏览器调用脚本,浏览器本身可能会进一步缓冲响应,然后再将其显示给您。
至于日志记录,最简单的方法是在某处选择一个文件,然后使用 file_put_contents() 打印任何内容你想要登录。请注意第三个参数的 FILE_APPEND 标志。
The loop itself looks fine. If it isn't updating your database, the error must be in your updateDB() function.
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.
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.
看起来您正在从命令行运行,在这种情况下您可能需要写入 stderr,以便没有缓冲。 $stderr = fopen('php://stderr', 'w');
对于日志记录,只需打开一个文件,写入文件,然后关闭它。 (fopen、fwrite、fclose);
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');
In the case of logging, just open a file, write to it, and close it. (fopen, fwrite, fclose);