views:

277

answers:

2

Hello,

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.

Thnks!

+3  A: 

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.

Atli
Hi, thank you for the reply. The strange thing is that the updateDB() function works correctly. When i remove the loop, and make a html meta refresh page of 1 sec everything works ok. Except for in the loop. And at the end of the file it just prints the contents of the echo, no errors. Is there some other method to invoke when you use sleep?
Saif Bechan
That's odd. I can't see a reason why the function would work differently that way. It's of course hard to say for certain, tho, without actually seeing the function. If you call the function five times in a row, each time followed by *sleep(1)*, does that change anything?... P.S. Added a bit of detail about the buffering.
Atli
Hi, everything works just fine now. I did had some errors in my updateDB() class, they where not really errors, but wrong programming. The database updates had to be checked against the current time in seconds. The times were defined one time before the loop, so nothing updated, and no errors.<br />But everything works fine now, the flush works too. thank you
Saif Bechan
A: 

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

Don