task, ['started' => now()->timestamp, 'running' => true]); self::put(self::HEARTBEAT, now()->timestamp); }); Event::listen(ScheduledTaskFinished::class, fn (ScheduledTaskFinished $event) => self::note($event->task, ['finished' => now()->timestamp, 'running' => false, 'ok' => true, 'seconds' => round($event->runtime, 2), 'error' => null])); Event::listen(ScheduledTaskFailed::class, fn (ScheduledTaskFailed $event) => self::note($event->task, ['finished' => now()->timestamp, 'running' => false, 'ok' => false, 'error' => SystemInfo::scrub(mb_substr($event->exception->getMessage(), 0, 300))])); } /** @return array */ public function report(): array { $beat = Cache::get(self::HEARTBEAT); $tasks = []; foreach ($this->events() as $event) { $last = Cache::get($this->key($event)); try { $next = $event->nextRunDate()->getTimestamp(); } catch (\Throwable) { $next = null; } $tasks[] = [ 'name' => $this->name($event), 'expression' => $event->expression, 'next' => $next, 'overlap' => $event->withoutOverlapping, 'background' => $event->runInBackground, 'last' => is_array($last) ? $last : null, ]; } usort($tasks, fn (array $a, array $b) => ($a['next'] ?? PHP_INT_MAX) <=> ($b['next'] ?? PHP_INT_MAX)); return [ 'tasks' => $tasks, // Null: nothing was noted yet (the cache may not keep things, or no task has been due since this was on). 'heartbeat' => is_int($beat) ? $beat : null, 'cron_line' => '* * * * * cd '.base_path().' && php artisan schedule:run >> /dev/null 2>&1', 'timezone' => (string) config('app.timezone'), ]; } /** @return list */ private function events(): array { // The schedule of an app is defined by its console kernel; a web request has not asked for it yet. try { app(Kernel::class)->bootstrap(); } catch (\Throwable) { // What was defined is still listed. } return array_values(app(Schedule::class)->events()); } private function name(ScheduledEvent $event): string { if ($event instanceof CallbackEvent) { return SystemInfo::scrub((string) $event->getSummaryForDisplay()); } $command = str_replace(["'".PHP_BINARY."'", "'artisan'", PHP_BINARY, 'artisan'], ['php', 'artisan', 'php', 'artisan'], (string) $event->command); return SystemInfo::scrub($event->description ?: trim($command)); } private function key(ScheduledEvent $event): string { return 'manager.system.schedule.'.md5($event->mutexName()); } /** @param array $values */ private static function note(ScheduledEvent $event, array $values): void { $key = 'manager.system.schedule.'.md5($event->mutexName()); $old = Cache::get($key); self::put($key, [...(is_array($old) ? $old : []), ...$values]); } private static function put(string $key, mixed $value): void { try { Cache::put($key, $value, now()->addDays(30)); } catch (\Throwable) { // A cache that is down must not stop a task from running. } } }