title: PHP - Stop and catch code which takes too long
body: <p>I'd like to limit a specific section of PHP to X seconds - if it takes longer, <em>kill</em> the currently executing code (just the section, not the entire script) and run an alternate code.</p>
  
  <p>Pseudo code example (Example use case here is an unstable API which is sometimes fast and other times its a black hole):</p>
  
  <pre><code>$completed = 1;
  $seconds = 60;
  while ($completed != -1 &amp;&amp; $completed &lt; 5) {
      limit ($seconds) {
          $api = new SomeAPI('user','secret','key');
          $data = $api-&gt;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";
      }
  }
  </code></pre>
  
  <p>HOWEVER, this should work for <em>anything</em>. Not just API/HTTP requests. E.g. an intensive database procedure.</p>
  
  <p><strong>In case you're reading too fast:</strong> <code>set_time_limit</code> and <code>max_execution_time</code> are <em>not</em> the answer as they affect the time limit for the <em>entire script</em> rather than just a section (unless I'm wrong on how those work, of course).</p>