瀏覽代碼

feat(cron): 引入获取定时任务事件并优化触发逻辑

- 新增 GetCronJobsEvent 用于收集所有定时任务类- 在 GatheringCrontabEventHook 中触发该事件以统一管理任务
- 使用事件机制替代直接遍历扩展中的任务类
- 添加日志输出功能,便于调试和监控定时任务执行情况
- 保留原有反射和注解解析逻辑,确保兼容性- 通过 push 方法将任务类加入事件集合中进行集中处理
runphp 6 月之前
父節點
當前提交
3542a56c94
共有 2 個文件被更改,包括 27 次插入8 次删除
  1. 10 0
      src/Event/GetCronJobsEvent.php
  2. 17 8
      src/Hook/GatheringCrontabEventHook.php

+ 10 - 0
src/Event/GetCronJobsEvent.php

@@ -0,0 +1,10 @@
+<?php
+declare(strict_types=1);
+namespace SixShop\System\Event;
+
+use think\Collection;
+
+class GetCronJobsEvent extends Collection
+{
+
+}

+ 17 - 8
src/Hook/GatheringCrontabEventHook.php

@@ -9,8 +9,10 @@ use SixShop\Core\Attribute\Cron;
 use SixShop\Core\Attribute\Hook;
 use SixShop\Core\Helper;
 use SixShop\System\Event\CrontabWorkerStartEvent;
+use SixShop\System\Event\GetCronJobsEvent;
 use SixShop\System\ExtensionManager;
 use think\App;
+use think\facade\Log;
 use Workerman\Crontab\Crontab;
 
 class GatheringCrontabEventHook
@@ -23,18 +25,25 @@ class GatheringCrontabEventHook
     public function onWorkerStart(): void
     {
         $extensionManager = $this->app->make(ExtensionManager::class);
+        $event = new GetCronJobsEvent();
+
         foreach (Helper::extension_name_list() as $extensionName) {
             $extension = $extensionManager->getExtension($extensionName);
             $cronJobs = $extension->getCronJobs();
             foreach ($cronJobs as $cronJobClass) {
-                $ref = new ReflectionClass($cronJobClass);
-                foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
-                    $attributes = $method->getAttributes(Cron::class);
-                    foreach ($attributes as $attribute) {
-                        $cronInstance = $attribute->newInstance();
-                        $name = $cronInstance->name ?: $cronJobClass . '@' . $method->getName();
-                        new Crontab($cronInstance->rule, [$this->app->make($cronJobClass), $method->getName()], $name);
-                    }
+                $event->push($cronJobClass);
+
+            }
+        }
+        $this->app->event->trigger($event);
+        foreach ($event as $cronJobClass) {
+            $ref = new ReflectionClass($cronJobClass);
+            foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
+                $attributes = $method->getAttributes(Cron::class);
+                foreach ($attributes as $attribute) {
+                    $cronInstance = $attribute->newInstance();
+                    $name = $cronInstance->name ?: $cronJobClass . '@' . $method->getName();
+                    new Crontab($cronInstance->rule, [$this->app->make($cronJobClass), $method->getName()], $name);
                 }
             }
         }