diff options
Diffstat (limited to 'library/X509/Scheduler.php')
-rw-r--r-- | library/X509/Scheduler.php | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/library/X509/Scheduler.php b/library/X509/Scheduler.php new file mode 100644 index 0000000..0963016 --- /dev/null +++ b/library/X509/Scheduler.php @@ -0,0 +1,59 @@ +<?php +// Icinga Web 2 X.509 Module | (c) 2018 Icinga GmbH | GPLv2 + +namespace Icinga\Module\X509; + +use Cron\CronExpression; +use Icinga\Application\Logger; +use React\EventLoop\Factory as Loop; + +class Scheduler +{ + protected $loop; + + public function __construct() + { + $this->loop = Loop::create(); + } + + public function add($name, $cronSchedule, callable $callback) + { + if (! CronExpression::isValidExpression($cronSchedule)) { + throw new \RuntimeException('Invalid cron expression'); + } + + $now = new \DateTime(); + + $expression = new CronExpression($cronSchedule); + + if ($expression->isDue($now)) { + $this->loop->futureTick($callback); + } + + $nextRuns = $expression->getMultipleRunDates(2, $now); + + $interval = $nextRuns[0]->getTimestamp() - $now->getTimestamp(); + + $period = $nextRuns[1]->getTimestamp() - $nextRuns[0]->getTimestamp(); + + Logger::info('Scheduling job %s to run at %s.', $name, $nextRuns[0]->format('Y-m-d H:i:s')); + + $loop = function () use (&$loop, $name, $callback, $period) { + $callback(); + + $nextRun = (new \DateTime()) + ->add(new \DateInterval("PT{$period}S")); + + Logger::info('Scheduling job %s to run at %s.', $name, $nextRun->format('Y-m-d H:i:s')); + + $this->loop->addTimer($period, $loop); + }; + + $this->loop->addTimer($interval, $loop); + } + + public function run() + { + $this->loop->run(); + } +} |