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

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  18.  */
  19. class StopWorkerOnRestartSignalListener implements EventSubscriberInterface
  20. {
  21.     public const RESTART_REQUESTED_TIMESTAMP_KEY 'workers.restart_requested_timestamp';
  22.     private CacheItemPoolInterface $cachePool;
  23.     private ?LoggerInterface $logger;
  24.     private float $workerStartedAt 0;
  25.     public function __construct(CacheItemPoolInterface $cachePoolLoggerInterface $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.             $this->logger?->info('Worker stopped because a restart was requested.');
  39.         }
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             WorkerStartedEvent::class => 'onWorkerStarted',
  45.             WorkerRunningEvent::class => 'onWorkerRunning',
  46.         ];
  47.     }
  48.     private function shouldRestart(): bool
  49.     {
  50.         $cacheItem $this->cachePool->getItem(self::RESTART_REQUESTED_TIMESTAMP_KEY);
  51.         if (!$cacheItem->isHit()) {
  52.             // no restart has ever been scheduled
  53.             return false;
  54.         }
  55.         return $this->workerStartedAt $cacheItem->get();
  56.     }
  57. }