WorkerStartCallback.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Framework\Bootstrap;
  12. use Hyperf\Contract\StdoutLoggerInterface;
  13. use Hyperf\Coordinator\Constants;
  14. use Hyperf\Coordinator\CoordinatorManager;
  15. use Hyperf\Framework\Event\AfterWorkerStart;
  16. use Hyperf\Framework\Event\BeforeWorkerStart;
  17. use Hyperf\Framework\Event\MainWorkerStart;
  18. use Hyperf\Framework\Event\OtherWorkerStart;
  19. use Psr\EventDispatcher\EventDispatcherInterface;
  20. use Swoole\Server as SwooleServer;
  21. class WorkerStartCallback
  22. {
  23. public function __construct(protected EventDispatcherInterface $dispatcher, protected StdoutLoggerInterface $logger)
  24. {
  25. }
  26. /**
  27. * Handle Swoole onWorkerStart event.
  28. */
  29. public function onWorkerStart(SwooleServer $server, int $workerId)
  30. {
  31. $this->dispatcher->dispatch(new BeforeWorkerStart($server, $workerId));
  32. if ($workerId === 0) {
  33. $this->dispatcher->dispatch(new MainWorkerStart($server, $workerId));
  34. } else {
  35. $this->dispatcher->dispatch(new OtherWorkerStart($server, $workerId));
  36. }
  37. if ($server->taskworker) {
  38. $this->logger->info("TaskWorker#{$workerId} started.");
  39. } else {
  40. $this->logger->info("Worker#{$workerId} started.");
  41. }
  42. $this->dispatcher->dispatch(new AfterWorkerStart($server, $workerId));
  43. CoordinatorManager::until(Constants::WORKER_START)->resume();
  44. }
  45. }