7

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).

Nathan J.B.
  • 10,215
  • 3
  • 33
  • 41
  • If the api relies on cURL, you can have a look at [timeout parameter](http://stackoverflow.com/questions/2582057/setting-curls-timeout-in-php). – moonwave99 Feb 20 '13 at 01:06
  • Assume `max_execution_time` is already set to ∞ – Nathan J.B. Feb 20 '13 at 01:06
  • Maybe something to try (if not using curl) would be using an async processing system, like gearman, according to SO they can be stopped midway though processing: http://stackoverflow.com/questions/2270323/stopping-gearman-workers-nicely – ChrisK Feb 20 '13 at 01:15

1 Answers1

3

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.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103