Last active
August 29, 2015 14:13
-
-
Save will1471/f89455d0813e22909273 to your computer and use it in GitHub Desktop.
Handle signals gracefully in long running workers
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 | |
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(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
will wait for the inner loop to complete