Page 1 of 1

Function Timeout

Posted: Wed Jan 24, 2007 2:47 am
by amir
Is there a way to timeout a function in PHP if it doesn't return a value in x seconds/microseconds?

For instance, if our primary MySQL database server is down, scripts will wait for 20 seconds while trying to connect. The scripts stack up on our web servers and cause a cascading failure. I need a way for mysql_connect to just return false or stop after one second and then I can write backup logic to display error messages to clients. Any suggestions? I'm aware of the set_time_limit function, but that will terminate the whole script. I need something to just terminate a function call.

TIA!

Posted: Wed Jan 24, 2007 6:03 am
by dibyendrah
You can add a logic in function like below :

Code: Select all

function some_func(){
   $start = microtime_float();
   //some logic
   $end = microtime_float();
   if(round($end - $start, 3)<5)
   //continue logic
   if(round($end - $start, 3)<10)
   //continue logic
   //continue logic
   if(round($end - $start, 3)<20) return false
   //continue logic
   return output;
}
I haven't implemented this kind of things, so, I'm lacking logic on this.

Posted: Wed Jan 24, 2007 6:04 am
by Mordred
Is there a way to timeout a function in PHP if it doesn't return a value in x seconds/microseconds?
Generally, no.

mysql.connect_timeout (php.ini setting) in your case. Ir should be settable by php.ini, local .htaccess files, or ini_set().

Posted: Sat Jan 27, 2007 5:19 am
by dibyendrah
Suppose, if some function takes 2 seconds to complete a job. If there had been a feature like threading or something like that, it would have been possible. So, Mordred might be right I guess.