Created
September 26, 2017 12:13
-
-
Save bubba-h57/ccce902e9aa373d00a4c4974626de8ad to your computer and use it in GitHub Desktop.
Have a function timeout on itself
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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