|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * 核心逻辑来自于 Hyperf 的 hyperf/crontab 组件. |
| 6 | + * @link https://www.hyperf.io |
| 7 | + * @document https://hyperf.wiki |
| 8 | + |
| 9 | + * @license https://github.com/hyperf/hyperf/blob/master/LICENSE |
| 10 | + * |
| 11 | + * @package think-swoole-crontab |
| 12 | + * @author OverNaive <[email protected]> |
| 13 | + */ |
| 14 | +namespace ThinkSwooleCrontab\Process; |
| 15 | + |
| 16 | +use Swoole\Timer; |
| 17 | +use Swoole\Server; |
| 18 | +use Swoole\Process; |
| 19 | +use think\App; |
| 20 | +use think\facade\Log; |
| 21 | +use ThinkSwooleCrontab\CrontabRegister; |
| 22 | +use ThinkSwooleCrontab\Scheduler; |
| 23 | +use ThinkSwooleCrontab\Strategy\CoroutineStrategy; |
| 24 | +use ThinkSwooleCrontab\Strategy\StrategyInterface; |
| 25 | + |
| 26 | +class CrontabDispatcherProcess |
| 27 | +{ |
| 28 | + /** |
| 29 | + * @var Server |
| 30 | + */ |
| 31 | + private $server; |
| 32 | + |
| 33 | + /** |
| 34 | + * @var CrontabRegister |
| 35 | + */ |
| 36 | + private $crontabRegister; |
| 37 | + |
| 38 | + /** |
| 39 | + * @var Scheduler |
| 40 | + */ |
| 41 | + private $scheduler; |
| 42 | + |
| 43 | + /** |
| 44 | + * @var StrategyInterface |
| 45 | + */ |
| 46 | + private $strategy; |
| 47 | + |
| 48 | + public function __construct(App $app) |
| 49 | + { |
| 50 | + $this->server = $app->get(Server::class); |
| 51 | + $this->crontabRegister = $app->make(CrontabRegister::class); |
| 52 | + $this->scheduler = $app->make(Scheduler::class); |
| 53 | + $this->strategy = $app->make(CoroutineStrategy::class); |
| 54 | + } |
| 55 | + |
| 56 | + public function handle(): void |
| 57 | + { |
| 58 | + $process = new Process(function (Process $process) { |
| 59 | + try { |
| 60 | + $this->crontabRegister->handle(); |
| 61 | + |
| 62 | + while (true) { |
| 63 | + $this->sleep(); |
| 64 | + $crontabs = $this->scheduler->schedule(); |
| 65 | + while (! $crontabs->isEmpty()) { |
| 66 | + $crontab = $crontabs->dequeue(); |
| 67 | + $this->strategy->dispatch($crontab); |
| 68 | + } |
| 69 | + } |
| 70 | + } catch (\Throwable $throwable) { |
| 71 | + Log::error($throwable->getMessage()); |
| 72 | + } finally { |
| 73 | + Timer::clearAll(); |
| 74 | + sleep(5); |
| 75 | + } |
| 76 | + }, false, 0, true); |
| 77 | + |
| 78 | + $this->server->addProcess($process); |
| 79 | + } |
| 80 | + |
| 81 | + private function sleep() |
| 82 | + { |
| 83 | + $current = date('s', time()); |
| 84 | + $sleep = 60 - $current; |
| 85 | + Log::debug('Crontab dispatcher sleep ' . $sleep . 's.'); |
| 86 | + $sleep > 0 && \Swoole\Coroutine::sleep($sleep); |
| 87 | + } |
| 88 | +} |
0 commit comments