Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule Artisan commands in a package?

I have a package that contains Artisan commands. I’ve registered these commands with Artisan via my service provider like so:

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    // Register Amazon Artisan commands
    $this->commands([
        'App\Marketplace\Amazon\Console\PostProductData',
        'App\Marketplace\Amazon\Console\PostProductImages',
        'App\Marketplace\Amazon\Console\PostProductInventory',
        'App\Marketplace\Amazon\Console\PostProductPricing',
    ]);
}

However, these commands need to be scheduled to run daily.

I know in app/Console/Kernel.php there is the schedule() method where you can register commands and their frequency, but how can I schedule commands in my package’s service provider instead?

like image 269
Martin Bean Avatar asked May 26 '15 11:05

Martin Bean


People also ask

How do I register my artisan command?

Laravel Artisan Creating and registering new artisan command after creating command you can register your command inside app/Console/Kernel. php class where you will find commands property. so you can add your command inside the $command array like : protected $commands = [ Commands\[commandName]::class ];


2 Answers

It took a lot of debugging and reading through Laravel's source to figure this out, but it turned out to be pretty simple. The trick is to wait until after the Application has booted to schedule the commands, since that is when Laravel defines the Schedule instance and then schedules commands internally. Hope this saves someone a few hours of painful debugging!

use Illuminate\Support\ServiceProvider;
use Illuminate\Console\Scheduling\Schedule;

class ScheduleServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->booted(function () {
            $schedule = $this->app->make(Schedule::class);
            $schedule->command('some:command')->everyMinute();
        });
    }

    public function register()
    {
    }
}
like image 73
Zane Avatar answered Sep 26 '22 23:09

Zane


In Laravel 6.10 and above:

use Illuminate\Support\ServiceProvider;
use Illuminate\Console\Scheduling\Schedule;

class ScheduleServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->callAfterResolving(Schedule::class, function (Schedule $schedule) {
            $schedule->command('some:command')->everyMinute();
        });
    }

    public function register()
    {
    }
}
like image 23
Kristopher Johnson Avatar answered Sep 22 '22 23:09

Kristopher Johnson