Skip to content

Instantly share code, notes, and snippets.

@will1471
Last active August 29, 2015 14:13
Show Gist options
  • Save will1471/f89455d0813e22909273 to your computer and use it in GitHub Desktop.
Save will1471/f89455d0813e22909273 to your computer and use it in GitHub Desktop.
Handle signals gracefully in long running workers
<?php
echo 'My PID = ' . posix_getpid() . "\n";
abstract class AbstractWorker
{
private $loopNumber = 0;
private $shouldRun = true;
public function __construct()
{
pcntl_signal(SIGTERM, function($signum) {
$this->shouldRun = false;
});
}
protected function getJob()
{
return $this->loopNumber++;
}
public function start()
{
while ($this->shouldRun) {
$this->doWork($this->getJob());
pcntl_signal_dispatch();
}
}
abstract public function doWork($job);
}
class Worker extends AbstractWorker
{
public function doWork($job)
{
for ($i = 0; $i < 5; $i++) {
// simulate stuff
print "{$job} {$i}\n";
sleep(1);
}
}
}
(new Worker)->start();
@will1471
Copy link
Author

$ kill $PID

will wait for the inner loop to complete

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