Adding a schedule:list command

A useful command for Laravel Artisan

Posted on January 19, 2016

If you’re like me, you probably like the schedule:run command introduced in Laravel 5.0. But one thing I don’t like is having to constantly look at app/Console/Kernel.php to see what my scheduled commands are.

So here’s a handy class to list them.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\Scheduling\Schedule;

class ScheduleList extends Command
{
    protected $signature = 'schedule:list';
    protected $description = 'List when scheduled commands are executed.';

    /**
     * @var Schedule
     */
    protected $schedule;

    /**
     * ScheduleList constructor.
     *
     * @param Schedule $schedule
     */
    public function __construct(Schedule $schedule)
    {
        parent::__construct();

        $this->schedule = $schedule;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $events = array_map(function ($event) {
            return [
                'cron' => $event->expression,
                'command' => static::fixupCommand($event->command),
            ];
        }, $this->schedule->events());

        $this->table(
            ['Cron', 'Command'],
            $events
        );
    }

    /**
     * If it's an artisan command, strip off the PHP
     *
     * @param $command
     * @return string
     */
    protected static function fixupCommand($command)
    {
        $parts = explode(' ', $command);
        if (count($parts) > 2 && $parts[1] === "'artisan'") {
            array_shift($parts);
        }

        return implode(' ', $parts);
    }
}

Just add the class to your app/Console/Commands directory and then edit app/Console/Kernel.php to add the the class to the $commands property.

Then, from your command line, do a php artisan schedule:list to get something like below:

+----------------+---------------------------------------------------------------+
| Cron           | Command                                                       |
+----------------+--------------------------------------------------------------+
| */10 * * * * * | 'artisan' maintain:api-queues                                 |
| 0,30 * * * * * | 'artisan' maintain:visits-needed --since=-1+hour              |
| 0 * * * * *    | 'artisan' sync:listings                                       |
| 15 * * * * *   | 'artisan' sync:accounts                                       |
| 30 * * * * *   | 'artisan' sync:web-properties                                 |
| 45 * * * * *   | 'artisan' sync:profiles                                       |
| 0 0 * * * *    | 'artisan' maintain:dates                                      |
+----------------+----------------------------------------------------------------+

Pretty nifty!

comments powered by Disqus