PHP code example of germanovn / php-overdaemon
1. Go to this page and download the library: Download germanovn/php-overdaemon library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once ('vendor/autoload.php' );
germanovn / php-overdaemon example snippets
namespace MyApp \Daemon ;
use GermanovN \OverDaemon \DaemonGate \InferiorDaemon ;
use GermanovN \OverDaemon \DaemonGate \InferiorDaemonRepository ;
class MyInferiorDaemonRepository implements InferiorDaemonRepository
{
private array $daemonCollection;
public function getAll () : array
{
return $this ->daemonCollection;
}
public function add (InferiorDaemon $daemon) : void
{
$this ->daemonCollection[] = $daemon;
}
public function count () : int
{
return count($this ->daemonCollection);
}
}
namespace MyApp \Daemon ;
use Exception ;
use GermanovN \OverDaemon \Daemon \Daemon ;
use GermanovN \OverDaemon \Daemon \StoppableDaemon ;
use GermanovN \OverDaemon \DaemonGate \InferiorDaemon ;
class MyDaemon extends StoppableDaemon implements InferiorDaemon
{
private int $pid;
public function devour (array $args = null) : int
{
$this ->pid = $args['pid' ];
try {
while ($this ->isRunningDaemon()) {
$execTime = $this ->getSomeLongTask();
if (null === $execTime) {
$this ->stopDaemon(SIGSTOP);
continue ;
}
$this ->logger->debug("Start '" . $this ->name() ."' PID: {$this->pid}" );
$this ->doTask($execTime);
$this ->logger->debug("End '" . $this ->name() ."' PID: {$this->pid}" );
}
return Daemon::EXIT_CODE_SUCCESS;
}
catch (Exception $e) {
$this ->logger->error(
sprintf('Code: %d. Message: %s' , $e->getCode(), $e->getMessage()),
$e->getTrace()
);
return Daemon::EXIT_CODE_ERROR;
}
}
private function getSomeLongTask () : ?int
{
$execTime = random_int(1 , 10 ) * 10 ;
return $execTime >= 90 ? null : $execTime;
}
private function doTask (int $task) : void
{
for ($i = 0 ; $i < $task; $i++) {
$this ->logger->debug($this ->name() . " PID: {$this->pid} " . $i);
usleep(10000 );
}
}
public function beforeDevour () : bool
{
return true ;
}
public function afterDevour () : void
{
}
public function name () : string
{
return self ::class;
}
}
pcntl_async_signals(true );
$sigHandler = SigHandler::instance();
pcntl_signal(SIGINT, [$sigHandler, 'handle' ]);
pcntl_signal(SIGTERM, [$sigHandler, 'handle' ]);
pcntl_signal(SIGHUP, [$sigHandler, 'handle' ]);
$repository = new MyInferiorDaemonRepository();
$repository->add(new MyDaemon());
$daemon = new OverDaemon(
new DaemonConfig(),
$repository,
$sigHandler
);
echo $daemon->devour();
bash
composer