Page 1 of 1

Continue while loop after a certain time

Posted: Thu Jun 29, 2006 7:04 am
by Grim...
I've got a while loop that performs a lot of calculations.
If the calculations take more than (say) 2 seconds, I want the loop to give up and move on to the next item (ie. continue).
Is this possible?

Posted: Thu Jun 29, 2006 7:08 am
by Chris Corbyn
Hmm... sleep() won't work.

Maybe set_time_limit() and register_shutdown_function() could be of help? Not sure on specifics off the top of my head.

Re: Continue while loop after a certain time

Posted: Thu Jun 29, 2006 7:12 am
by aerodromoi
Grim... wrote:I've got a while loop that performs a lot of calculations.
If the calculations take more than (say) 2 seconds, I want the loop to give up and move on to the next item (ie. continue).
Is this possible?
How about using microtime to define a break statement?

Posted: Thu Jun 29, 2006 7:27 am
by Grim...
Then I'd have to include the if statement for microtime in each part of the while loop, surely (in case it gets stuck in a sub-loop)?

I was thinking about set_time_limit - I'll look into that now.

Posted: Thu Jun 29, 2006 7:55 am
by aerodromoi
Grim... wrote:Then I'd have to include the if statement for microtime in each part of the while loop, surely (in case it gets stuck in a sub-loop)?

I was thinking about set_time_limit - I'll look into that now.
Is your server running in safemode?

Posted: Thu Jun 29, 2006 8:20 am
by Grim...
Nope.

Posted: Fri Jun 30, 2006 12:53 pm
by Robert Plank
If you're on unix look at these functions: http://php.net/pcntrl

Hopefully you know how to do multithreaded programming. Have a child process for each calculation. If the script finds out it's a child, set the timeout to 2. Then the mother process loops through and cleans up the zombies if they're dead. I don't know how you would share memory, I you might have to use a database for these guys to store their calculations, or maybe if static variables will carry over, I don't know. You'll have to mess around.

Posted: Fri Jun 30, 2006 6:16 pm
by bokehman
If you are worried about getting stuck in a loop just set up an iteration counter.

Code: Select all

if(++$i === 1000) break;

Posted: Fri Jun 30, 2006 6:21 pm
by Benjamin
Why not something like...

Code: Select all

function MicroTimeFloat() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

$Start = MicroTimeFloat();

while (1 < 2) {
  if (($Start - MicrotimeFloat()) > 2) {
    break;
  }

  // more code here
}