I need a function that will throw a catchable exception after a callable function has taken to long to complete it's task.
Note: I am not referring to the max execution time for a PHP script.
The function should work like the call_user_func
except that it takes a time limit in seconds for the callable.
function task() {
// does a lot of work...
}
try {
call_user_func('task', 30); // limit to 30 seconds
} catch (TimeoutException $ex) {
// ....
}
I can not add custom logic to the task
function to throw an exception on it's own. The idea is to force the callable methods to abort or fail after X number of seconds.
I have CLI scripts that I want to regulate how long they take to complete a task.
You could use EvTimer. However, you have to install the Ev Package since it's not part of PHP. You can do that with pecl install ev
<?php
function task(){
// DOES A LOT OF WORK...
}
function runTaskWithin($seconds) {
// SET UP A TIMER TO FIRE AFTER X-SECONDS
$evT = new EvTimer($seconds, 0, function ($seconds) {
throw(new Exception("{$seconds} Seconds has elapsed since Execution began... Better rest, Now."));
});
}
// ONCE 30 SECONDS PASSES A NEW EXCEPTION WILL BE THROWN...
// NON-BLOCKING...
try {
runTaskWithin(30); // LIMIT TO 30 SECONDS
} catch (Exception $ex) {
// ....
}