-
-
Save Danack/5740695186c0ddd72610bfb6ff938d9e to your computer and use it in GitHub Desktop.
run_with_exit.php
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 | |
/** | |
* Self-contained monitoring system for system signals | |
* returns true if a 'graceful exit' like signal is received. | |
* | |
* We don't listen for SIGKILL as that needs to be an immediate exit, | |
* which PHP already provides. | |
* @return bool | |
*/ | |
function checkSignalsForExit() | |
{ | |
static $initialised = false; | |
static $needToExit = false; | |
$fnSignalHandler = function ($signalNumber) use (&$needToExit) { | |
$needToExit = true; | |
}; | |
if ($initialised === false) { | |
pcntl_signal(SIGINT, $fnSignalHandler, false); | |
pcntl_signal(SIGQUIT, $fnSignalHandler, false); | |
pcntl_signal(SIGTERM, $fnSignalHandler, false); | |
pcntl_signal(SIGHUP, $fnSignalHandler, false); | |
pcntl_signal(SIGUSR1, $fnSignalHandler, false); | |
$initialised = true; | |
} | |
pcntl_signal_dispatch(); | |
return $needToExit; | |
} | |
/** | |
* Repeatedly calls a callable until it's time to stop | |
* | |
* @param callable $callable - the thing to run | |
* @param int $secondsBetweenRuns - the minimum time between runs | |
* @param int $sleepTime - the time to sleep between runs | |
* @param int $maxRunTime - the max time to run for, before returning | |
*/ | |
function continuallyExecuteCallable($callable, int $secondsBetweenRuns, int $sleepTime, int $maxRunTime) | |
{ | |
$startTime = microtime(true); | |
$lastRuntime = 0; | |
$finished = false; | |
echo "starting continuallyExecuteCallable \n"; | |
while ($finished === false) { | |
$shouldRunThisLoop = false; | |
if ($secondsBetweenRuns === 0) { | |
$shouldRunThisLoop = true; | |
} | |
else if ((microtime(true) - $lastRuntime) > $secondsBetweenRuns) { | |
$shouldRunThisLoop = true; | |
} | |
if ($shouldRunThisLoop === true) { | |
$callable(); | |
$lastRuntime = microtime(true); | |
} | |
if (checkSignalsForExit()) { | |
break; | |
} | |
if ($sleepTime > 0) { | |
sleep($sleepTime); | |
} | |
if ((microtime(true) - $startTime) > $maxRunTime) { | |
echo "Reach maxRunTime - finished = true\n"; | |
$finished = true; | |
} | |
} | |
echo "Finishing continuallyExecuteCallable\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment