Skip to content

Instantly share code, notes, and snippets.

@avalanche123
Created July 10, 2012 19:12
Show Gist options
  • Save avalanche123/3085581 to your computer and use it in GitHub Desktop.
Save avalanche123/3085581 to your computer and use it in GitHub Desktop.
timeouts in php
<?php
class TimeoutException extends RuntimeException {}
class Timeout
{
private $active;
public function set($seconds)
{
$this->active = true;
declare(ticks = 1);
pcntl_signal(SIGALRM, array($this, 'handle'), true);
pcntl_alarm($seconds);
}
public function clear()
{
$this->active = false;
}
public function handle($signal)
{
echo "received signal\n";
if ($this->active) {
throw new TimeoutException();
}
}
}
$timeout = new Timeout();
$start = microtime(true);
try {
echo "setting timeout to 1 second\n";
$timeout->set(1); // set a 1 second timeout
echo "sleeping for 10 seconds\n";
sleep(10); // some long running operation...
echo "clearing 1 second timeout\n";
$timeout->clear(); // clear timeout
} catch(TimeoutException $e) {
// timed out
echo "caught a TimeoutException\n";
}
$total = microtime(true) - $start;
echo "time spent {$total}\n";
@ornicar
Copy link

ornicar commented Jul 10, 2012

yummy :)

@datiecher
Copy link

I tip my hat to you, sir!

@asennoussi
Copy link

Fantastic!

@sharmashivanand
Copy link

Is there a way to incorporate pcntl_signal_dispatch in this function? I've seen that it doesn't work sometimes. Pls see https://www.php.net/manual/en/function.pcntl-alarm.php#122637

@dimer47
Copy link

dimer47 commented Jun 6, 2021

Thanks 👍🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment