1. Go to this page and download the library: Download snailweb/php-daemon 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');
/* Start to develop here. Best regards https://php-download.com/ */
snailweb / php-daemon example snippets
final class AdminNotifierProcessor implements \Snailweb\Daemon\Processor\ProcessorInterface
{
private $dao;
private $notifier;
// Inject your dependencies
public function __construct(DAO $dao, Notifier $notifier)
{
$this->dao = $dao;
$this->notifier = $notifier;
}
// Initialize stuff
public function setUp(): void
{
$this->dao->connect();
$this->notifier->setEmail('[email protected]');
}
// CLear stuff
public function tearDown(): void
{
$this->dao->disconnect();
unset($this->dao, $this->notifier);
}
// Do your stuff
public function process(): void
{
$results = $this->dao->query("SELECT id, message FROM notifications WHERE status='notify'");
foreach ($results as $result) {
$this->notifier->notify($result->message);
$this->dao->query("UPDATE table SET status = 'notified' WHERE id = ?", $results->id);
}
}
}
$processor = new AdminNotifierProcessor($dao, $notifier);
$daemon = new \Snailweb\Daemon\Daemon($processor);
$daemon->run();
$strategy = new Snailweb\Daemon\Strategy\Iteration(5);
$daemon->run($strategy);
$strategy = new Snailweb\Daemon\Strategy\Timer(60);
$daemon->run($strategy);
$daemon->setOptions([
'run_ttl' => 86400, // the daemon will stop after 1 day of runtime
'run_memory_limit' => 128, // the daemon will stop when he reached 128MB of memory usage
'process_min_exec_time' => 100, // The minimum time between 2 process execution (to avoid CPU overload when your process has nothing do)
]);
final class MySignalHandler extends \Snailweb\Daemon\Signals\Handler\AbstractSignalsHandler
{
public function handle(int $signal, Snailweb\Daemon\Daemon $daemon): void
{
switch ($signal) {
case SIGINT:
// Change daemon's behaviour
// Apply an other processor
$daemon->setProcessor(new ProperExitProcessor());
// For only 10 more iterations
$daemon->setStrategy(new \Snailweb\Daemon\Strategy\Iteration(10));
break;
case SIGTERM:
// Instantly stop our script
$daemon->stop();
break;
}
}
}
$processor = new AdminNotifierProcessor();
$signals = new \Snailweb\Daemon\Signals\Signals([SIGINT, SIGTERM]);
$signalsListener = new \Snailweb\Daemon\Signals\Listener\SignalsListener();
$signalsHandler = new MySignalHandler();
$signalsManager = new \Snailweb\Daemon\Signals\Manager\SignalsManager($signals, $signalsListener, $signalsHandler);
$daemon = new \Snailweb\Daemon\Daemon($processor, $signalsManager);
$daemon->run();
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.