正在显示
1 个修改的文件
包含
27 行增加
和
5 行删除
| @@ -9,6 +9,7 @@ class StreamLogger | @@ -9,6 +9,7 @@ class StreamLogger | ||
| 9 | protected int $flushSize = 50; // 缓冲条数 | 9 | protected int $flushSize = 50; // 缓冲条数 |
| 10 | protected int $flushInterval = 1000; // 最长缓存时间(毫秒) | 10 | protected int $flushInterval = 1000; // 最长缓存时间(毫秒) |
| 11 | protected array $lastWrite = []; // 每个 channel 上次写盘时间戳(毫秒) | 11 | protected array $lastWrite = []; // 每个 channel 上次写盘时间戳(毫秒) |
| 12 | + protected bool $timerCreated = false; // 是否已创建定时器 | ||
| 12 | 13 | ||
| 13 | public function __construct(string $basePath = null) | 14 | public function __construct(string $basePath = null) |
| 14 | { | 15 | { |
| @@ -23,13 +24,34 @@ class StreamLogger | @@ -23,13 +24,34 @@ class StreamLogger | ||
| 23 | if (!is_dir($this->basePath)) { | 24 | if (!is_dir($this->basePath)) { |
| 24 | mkdir($this->basePath, 0777, true); | 25 | mkdir($this->basePath, 0777, true); |
| 25 | } | 26 | } |
| 27 | + // 自动延迟启动(防止主程序部分服务未完成初始化。) | ||
| 28 | + $this->bootTickSafely(); | ||
| 29 | + } | ||
| 30 | + protected function bootTickSafely() | ||
| 31 | + { | ||
| 32 | + // 如果已经创建,避免重复 | ||
| 33 | + if (!empty($this->timerCreated)) { | ||
| 34 | + return; | ||
| 35 | + } | ||
| 36 | + $this->timerCreated = true; | ||
| 26 | 37 | ||
| 27 | - // 启动定时器(仅 Swoole 环境有效) | ||
| 28 | - if (class_exists(\Swoole\Timer::class)) { | ||
| 29 | - \Swoole\Timer::tick(1000, function () { | ||
| 30 | - $this->flushByInterval(); | ||
| 31 | - }); | 38 | + // 如果已经在协程环境 → 直接创建 tick |
| 39 | + if (\Swoole\Coroutine::getCid() > 0) { | ||
| 40 | + $this->startTick(); | ||
| 41 | + return; | ||
| 32 | } | 42 | } |
| 43 | + | ||
| 44 | + // 不在协程 → 用 defer 延迟到协程环境创建后 | ||
| 45 | + \Swoole\Coroutine::defer(function () { | ||
| 46 | + $this->startTick(); | ||
| 47 | + }); | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + protected function startTick() | ||
| 51 | + { | ||
| 52 | + \Swoole\Timer::tick(1000, function () { | ||
| 53 | + $this->flushByInterval(); | ||
| 54 | + }); | ||
| 33 | } | 55 | } |
| 34 | 56 | ||
| 35 | public function log($channel, $content): void | 57 | public function log($channel, $content): void |
-
请 注册 或 登录 后发表评论