Function Timeout

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
amir
Forum Contributor
Posts: 287
Joined: Sat Oct 07, 2006 4:28 pm

Function Timeout

Post 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!
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post 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.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post 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().
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post 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.
Post Reply