首页 > 解决方案 > Laravel 5.5: Want to run multiple cronjobs through kernel.php under App/Console

问题描述

I want to run different cronjobs like deleting users, send coupon codes to users, send greeting to users who joined between specified dates and etc. Can I do the same by opening the App\Console\Kernel.php and write the command as below:

protected $commands = [
         '\App\Console\Commands\DeleteUsers',
         '\App\Console\Commands\SendCouponCode',
         '\App\Console\Commands\SendGreetings',
];

protected function schedule(Schedule $schedule)
{        
 $schedule->command('DeleteUsers:deleteuserscronjob')->everyMinute();
 $schedule->command('SendCouponCode:sendcouponcodecronjob')->everyMinute();
 $schedule->command('SendGreetings:sendgreetingscronjob')->everyMinute();
}

Also, can someone suggest how to run cronjobs by calling only the methods under controllers and not by commands, as like below?

App\Http\Controllers\MyController1@MyAction1

And,

App\Http\Controllers\MyController2@MyAction2

标签: laravellaravel-5

解决方案


Using kernel.php to schedule tasks is the correct way to do it according to the Laravel framework.

However, if you want to execute a method in one of your controllers instead of creating a command for it, you can do it like so:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        MyController::myStaticMethod();
    })->daily();
}

For running a schedules task via a command:

protected $commands = [
    Commands\MyCommand::class,
];

protected function schedule(Schedule $schedule)
{
    $schedule->command('mycommand:run')->withoutOverlapping();
}

Then in app\Console\Commands\MyCommand.php:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class MyCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mycommand:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Description of my command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // PUT YOUR TASK TO BE RUN HERE

    }
}

推荐阅读