StopWorkersCommand.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\Command;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Style\SymfonyStyle;
  17. use Symfony\Component\Messenger\EventListener\StopWorkerOnRestartSignalListener;
  18. /**
  19. * @author Ryan Weaver <ryan@symfonycasts.com>
  20. */
  21. class StopWorkersCommand extends Command
  22. {
  23. protected static $defaultName = 'messenger:stop-workers';
  24. private $restartSignalCachePool;
  25. public function __construct(CacheItemPoolInterface $restartSignalCachePool)
  26. {
  27. $this->restartSignalCachePool = $restartSignalCachePool;
  28. parent::__construct();
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. protected function configure(): void
  34. {
  35. $this
  36. ->setDefinition([])
  37. ->setDescription('Stop workers after their current message')
  38. ->setHelp(<<<'EOF'
  39. The <info>%command.name%</info> command sends a signal to stop any <info>messenger:consume</info> processes that are running.
  40. <info>php %command.full_name%</info>
  41. Each worker command will finish the message they are currently processing
  42. and then exit. Worker commands are *not* automatically restarted: that
  43. should be handled by a process control system.
  44. EOF
  45. )
  46. ;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function execute(InputInterface $input, OutputInterface $output)
  52. {
  53. $io = new SymfonyStyle($input, $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output);
  54. $cacheItem = $this->restartSignalCachePool->getItem(StopWorkerOnRestartSignalListener::RESTART_REQUESTED_TIMESTAMP_KEY);
  55. $cacheItem->set(microtime(true));
  56. $this->restartSignalCachePool->save($cacheItem);
  57. $io->success('Signal successfully sent to stop any running workers.');
  58. return 0;
  59. }
  60. }