Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Stop and catch code which takes too long

Tags:

php

I'd like to limit a specific section of PHP to X seconds - if it takes longer, kill the currently executing code (just the section, not the entire script) and run an alternate code.

Pseudo code example (Example use case here is an unstable API which is sometimes fast and other times its a black hole):

$completed = 1;
$seconds = 60;
while ($completed != -1 && $completed < 5) {
    limit ($seconds) {
        $api = new SomeAPI('user','secret','key');
        $data = $api->getStuff('user="bob"');
        $completed = -1;
    } catch () {
        $completed++;
        sleep(10);
    }
}
if ($completed === 5) echo "Error: API black-hole'd 5 times.\n";
else {
    //Notice: data processing is OUTSIDE of the time limit
    foreach ($data as $row) {
          echo $row['name'].': '.$row['message']."\n";
    }
}

HOWEVER, this should work for anything. Not just API/HTTP requests. E.g. an intensive database procedure.

In case you're reading too fast: set_time_limit and max_execution_time are not the answer as they affect the time limit for the entire script rather than just a section (unless I'm wrong on how those work, of course).

like image 433
Nathan J.B. Avatar asked Feb 20 '13 01:02

Nathan J.B.


1 Answers

In the case of an API call, I would suggest using cURL, for which you can set a specific timeout for the API call.

For generic use, you can look at forking processes, which would give you the ability to time each process and kill it if it exceeds the expected time.

Of course if the section of code might be subject to long execution times due to a highly repetitive loop structure, you can provide your own timers to break out of the loop after a specified time interval.

I might not have directly answered your question, but really the point I wanted to get to is that you might have to use a different approach depending on what the code block actually does.

like image 147
Mike Brant Avatar answered Oct 25 '22 15:10

Mike Brant