Edit report at https://bugs.php.net/bug.php?id=3830&edit=1

 ID:                 3830
 Comment by:         shiranai7 at hotmail dot com
 Reported by:        wico at cnh dot nl
 Summary:            Function to timeout/break off a function
 Status:             Open
 Type:               Feature/Change Request
 Package:            Scripting Engine problem
 Operating System:   *
 PHP Version:        *
 Block user comment: N
 Private report:     N

 New Comment:

Yes you can do this using ticks, because you can throw an exception from the 
function to interrupt the script's flow.

Here's an example. I have testes it (PHP 5.4.0) and it worked very well.
------------------
// exception class and function
class TimeoutException extends Exception {}
function time_limit($end_time){ if(time() >= $end_time) throw new 
TimeoutException; }

// usage example
register_tick_function('time_limit', time() + 2); // time limit is 2 seconds
try {
    
    // here goes the stuff we need to limit
    declare(ticks = 20) {
        // comment out either line to test
        /* this line will cause timeout */ while(true) { $foo = 1 + 1; }
        /* this line would finish in time */ sleep(1);
    }

    // if the script gets here the stuff finished in time
    unregister_tick_function('time_limit');
    echo "finished in time";

} catch(TimeoutException $e) {

    // if the script gets here the stuff took too long
    unregister_tick_function('time_limit');
    echo "took too long";

}


Previous Comments:
------------------------------------------------------------------------
[2002-01-28 18:14:29] tor...@php.net

No, you can't. :) The ticks stuff won't stop a function which
is tied up in a function call such as sleep. This does sound
like something which would be nice to have...

I've also updated the version number on this to 4.2.0-dev


Torben

------------------------------------------------------------------------
[2002-01-28 16:54:34] yohg...@php.net

register_tick_function() can be used.

------------------------------------------------------------------------
[2000-07-31 22:49:52] waldschr...@php.net

well, could be quite nice

------------------------------------------------------------------------
[2000-03-14 11:27:16] wico at cnh dot nl

Hiya,

i did like to see a function wich breaks into another when it take to long:

<?

funtion Hour () {
        sleep 3600;
}

// break after say 2 secs
$timeout = Timeout_function(hour(), 2);
if ($timeout) {
        // function took to long
} else {
        // function compledet normal
}

?>

------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=3830&edit=1

Reply via email to