开发者

PHP sleep() inside loop not updating DB

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.

开发者_JS百科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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜