PHP:在运行时打印状态消息
我正在开发一个长时间运行的 php 脚本,该脚本编译从多个来源抓取的信息、组织它们并将它们缓存在数据库中。
由于该脚本的运行时间非常长,因此我想打印运行时状态报告以跟踪进度。
for ($i = 1; $i<= 10; $i++) {
echo "Starting iteration #$i\n";
set_time_limit(40);
echo "Time Limit set, starting 10 second sleep.\n";
sleep(10);
echo "Finishing iteration #$i\n\n";
}
echo "Iterations Finished.";
会输出:
开始迭代#1
时间限制已设置,开始 10 秒睡眠
然后等待 10 秒并输出:
完成迭代#1
开始迭代#2
时间限制已设置,开始 10 秒睡眠
,然后在 php 完成解析之前,它将输出:
迭代已完成。
实现这一目标的最佳方法是什么?
I'm developing a long running php script that compiles scraped information from multiple sources, organizes them, and caches them in a database.
As this script has a very high runtime, I'd like to print out runtime status reports in order to track the progress.
for ($i = 1; $i<= 10; $i++) {
echo "Starting iteration #$i\n";
set_time_limit(40);
echo "Time Limit set, starting 10 second sleep.\n";
sleep(10);
echo "Finishing iteration #$i\n\n";
}
echo "Iterations Finished.";
would output:
Starting iteration #1
Time Limit set, starting 10 second sleep
then wait 10 seconds and output:
Finishing iteration #1
Starting iteration #2
Time Limit set, starting 10 second sleep
then right before the php finishes parsing, it will output:
Iterations Finished.
What is the best way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您从 CLI 运行 PHP,则可以直接输出到 stdout,而无需等待脚本
最后,使用:
如果从 CGI 运行,这对于像这样的脚本来说真的很糟糕,您必须使用flush()来更改缓冲区的行为方式;
If you are running PHP from the CLI you can output directly to stdout, without having to wait for the script
to end, using :
If run from CGI, which would be really bad for a script like this, you would have to change how the buffer acts with flush();
尝试将运行时状态报告写入文件,然后使用 ajax 查看文件的实时更新,按照以下问题: Live feed of an waiting file
Try writing the runtime status reports to a file, then viewing live updates of the file using ajax, per this question: Live feed of an updating file