vendor/symfony/messenger/EventListener/StopWorkerOnRestartSignalListener.php line 37

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Messenger\EventListener;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\Messenger\Event\WorkerRunningEvent;
  15. use Symfony\Component\Messenger\Event\WorkerStartedEvent;
  16. /**
  17.  * @author Ryan Weaver <ryan@symfonycasts.com>
  18.  */
  19. class StopWorkerOnRestartSignalListener implements EventSubscriberInterface
  20. {
  21.     public const RESTART_REQUESTED_TIMESTAMP_KEY 'workers.restart_requested_timestamp';
  22.     private $cachePool;
  23.     private $logger;
  24.     private $workerStartedAt;
  25.     public function __construct(CacheItemPoolInterface $cachePool, ?LoggerInterface $logger null)
  26.     {
  27.         $this->cachePool $cachePool;
  28.         $this->logger $logger;
  29.     }
  30.     public function onWorkerStarted(): void
  31.     {
  32.         $this->workerStartedAt microtime(true);
  33.     }
  34.     public function onWorkerRunning(WorkerRunningEvent $event): void
  35.     {
  36.         if ($this->shouldRestart()) {
  37.             $event->getWorker()->stop();
  38.             if (null !== $this->logger) {
  39.                 $this->logger->info('Worker stopped because a restart was requested.');
  40.             }
  41.         }
  42.     }
  43.     public static function getSubscribedEvents()
  44.     {
  45.         return [
  46.             WorkerStartedEvent::class => 'onWorkerStarted',
  47.             WorkerRunningEvent::class => 'onWorkerRunning',
  48.         ];
  49.     }
  50.     private function shouldRestart(): bool
  51.     {
  52.         $cacheItem $this->cachePool->getItem(self::RESTART_REQUESTED_TIMESTAMP_KEY);
  53.         if (!$cacheItem->isHit()) {
  54.             // no restart has ever been scheduled
  55.             return false;
  56.         }
  57.         return $this->workerStartedAt $cacheItem->get();
  58.     }
  59. }