Skip to content

Instantly share code, notes, and snippets.

@bubba-h57
Created September 26, 2017 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bubba-h57/ccce902e9aa373d00a4c4974626de8ad to your computer and use it in GitHub Desktop.
Save bubba-h57/ccce902e9aa373d00a4c4974626de8ad to your computer and use it in GitHub Desktop.
Have a function timeout on itself
<?php
try {
test();
} catch (TimeoutException $e) {
$e->handle();
} catch (Throwable $t) {
printf('Some other error occured. %s', $t->getMessage());
}
class Timer
{
public function setTimeout($seconds)
{
declare(ticks = 1);
pcntl_signal(SIGALRM, array($this, 'handler'), true);
pcntl_alarm($seconds);
}
public function handler(int $signal)
{
throw new \TimeoutException(sprintf("Received Timeout Signal: %d\n", $signal));
}
}
class TimeoutException extends \RuntimeException
{
public function handle()
{
print $this->getMessage();
}
}
function test($timeout = 5, $length = 100)
{
$timer = new Timer();
printf("Timeout: %d, Length: %d\n", $timeout, $length);
$timer->setTimeout($timeout);
for($i=0;$i<=$length;$i++)
{
printf("%d\n", fibonacci($i));
}
}
function fibonacci($n) {
//make it look like we are working.
usleep(150000);
return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment