|
|
@@ -8,6 +8,8 @@ use ReflectionClass;
|
|
|
use ReflectionMethod;
|
|
|
use SixShop\Core\Attribute\Cron;
|
|
|
use SixShop\Core\Attribute\Hook;
|
|
|
+use SixShop\System\Event\CronJobAfterEvent;
|
|
|
+use SixShop\System\Event\CronJobBeforeEvent;
|
|
|
use SixShop\System\Event\CrontabWorkerStartEvent;
|
|
|
use SixShop\System\Event\GetCronJobsEvent;
|
|
|
use SixShop\System\ExtensionManager;
|
|
|
@@ -23,6 +25,38 @@ class GatheringCrontabEventHook
|
|
|
{
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 包装回调函数,在任务执行前后触发事件
|
|
|
+ */
|
|
|
+ private function wrapCallback(callable $callback, string $name, string $rule, object $target): callable
|
|
|
+ {
|
|
|
+ return function () use ($callback, $name, $rule, $target) {
|
|
|
+ $this->app->event->trigger(new CronJobBeforeEvent($name, $rule, $target));
|
|
|
+
|
|
|
+ $startTime = microtime(true);
|
|
|
+ $throwable = null;
|
|
|
+ $result = null;
|
|
|
+
|
|
|
+ try {
|
|
|
+ $result = $callback();
|
|
|
+ } catch (\Throwable $e) {
|
|
|
+ $throwable = $e;
|
|
|
+ Log::error("Cron job [{$name}] failed: " . $e->getMessage());
|
|
|
+ }
|
|
|
+
|
|
|
+ $duration = microtime(true) - $startTime;
|
|
|
+
|
|
|
+ $this->app->event->trigger(new CronJobAfterEvent(
|
|
|
+ name: $name,
|
|
|
+ rule: $rule,
|
|
|
+ target: $target,
|
|
|
+ result: $result,
|
|
|
+ duration: round($duration, 4),
|
|
|
+ throwable: $throwable,
|
|
|
+ ));
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* @throws \ReflectionException
|
|
|
*/
|
|
|
@@ -48,7 +82,10 @@ class GatheringCrontabEventHook
|
|
|
foreach ($objectAttts as $attribute) {
|
|
|
$cronInstance = $attribute->newInstance();
|
|
|
if (is_callable($cronJob)) {
|
|
|
- new Crontab($cronInstance->rule, $cronJob, $cronInstance->name ?: $cronJobClass);
|
|
|
+ $name = $cronInstance->name ?: $cronJobClass;
|
|
|
+ $callback = $this->wrapCallback($cronJob, $name, $cronInstance->rule, $cronJob);
|
|
|
+ new Crontab($cronInstance->rule, $callback, $name);
|
|
|
+ Log::info("Cron job registered [{$name}] rule={$cronInstance->rule}");
|
|
|
} else {
|
|
|
Log::warning("Cron job {$cronJobClass} is not callable");
|
|
|
}
|
|
|
@@ -58,7 +95,9 @@ class GatheringCrontabEventHook
|
|
|
foreach ($attributes as $attribute) {
|
|
|
$cronInstance = $attribute->newInstance();
|
|
|
$name = $cronInstance->name ?: $cronJobClass . '@' . $method->getName();
|
|
|
- new Crontab($cronInstance->rule, [$cronJob, $method->getName()], $name);
|
|
|
+ $callback = $this->wrapCallback([$cronJob, $method->getName()], $name, $cronInstance->rule, $cronJob);
|
|
|
+ new Crontab($cronInstance->rule, $callback, $name);
|
|
|
+ Log::info("Cron job registered [{$name}] rule={$cronInstance->rule}");
|
|
|
}
|
|
|
}
|
|
|
}
|