fetzi.dev

Monitoring your Laravel Schedule

2 minutes

Getting an overview of your scheduled tasks in Laravel and when they run, can be quite tricky. In your console Kernel class you define your scheduled commands, but you do not get any information about the defined schedules out of the kernel.

<?php

protected function schedule(Schedule $schedule)
{
    $schedule->command(ExampleCommand::class)
        ->everyFiveMinutes()
        ->appendOutputTo(storage_path('logs/examplecommand.log'));
}

Constructing the Schedule

By moving the $schedule->command calls into a seperate class you get the possibility to access the schedule information from another context.

<?php

class ScheduleService
{
    public function registerCommands(Schedule $schedule)
    {
        $schedule->command(ExampleCommand::class)
            ->everyFiveMinutes()
            ->appendOutputTo(storage_path('logs/examplecommand.log'));
    }
}

And in your console kernel you simply call the registerCommands method.

Getting information about scheduled commands

It might be interesting to get a list of all scheduled commands, the cron expression and the expected execution time. To be able to accomplish this we need to ask the container for an Schedule instance and apply our scheduled commands on it.

By calling the $schedule->events() method you get an array of all Event instances scheduled. By using the powerful CronExpression class you can get the next run date of a certain command.

<?php

class ScheduleService
{
    // ...

    public function getCommands()
    {
        $schedule = app(Schedule::class);

        $this->registerCommands($schedule);

        $scheduledCommands = collect($schedule->events())
            ->map(function ($event) {
                $expression = CronExpression::factory($event->expression);

                return [
                    'command' => $event->command,
                    'expression' => $event->expression,
                    'next-execution' => $expression->getNextRunDate()
                ];
            });

        return $scheduledCommands;
    }
}

This service method can now be used in a web application for providing information about the schedule without actually executing any of the defined scheduled tasks.

For detailed information about the laravel scheduler please see the laravel documentation.

Resources

This might be also interesting

Do you enjoy reading my blog?

sponsor me at ko-fi