Skip to content

Instantly share code, notes, and snippets.

@Nex-Otaku
Created February 26, 2021 13:47
Show Gist options
  • Save Nex-Otaku/d82874537375abd24db878c1d46ec372 to your computer and use it in GitHub Desktop.
Save Nex-Otaku/d82874537375abd24db878c1d46ec372 to your computer and use it in GitHub Desktop.
Detecting system signals to gracefully stop PHP script
/**
* Usage:
*
* $breakSignalDetector = new BreakSignalDetector();
* $breakSignalDetector->registerSignalHandler();
*
* while (...) // Some long running cycle
* {
* ...
* if ($breakSignalDetector->isTerminated()) {
* break;
* }
* }
*/
class BreakSignalDetector
{
/** @var bool */
private $isTerminated = false;
public function registerSignalHandler(): void
{
pcntl_async_signals(true);
pcntl_signal(SIGINT, [$this, 'terminate']);
pcntl_signal(SIGTERM, [$this, 'terminate']);
}
public function terminate(): void
{
$this->isTerminated = true;
}
public function isTerminated(): bool
{
return $this->isTerminated;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment