添加到Schedule Laravel后如何立即执行任务?

时间:2018-07-09 07:23:25

标签: laravel cron schedule

我有下一个代码:

foreach ($tasks as $task) {
    $schedule->command(TaskCommand::class, [$task->id])->hourly();
}

我动态添加了此任务。

如何在添加到计划后立即执行任务,之后又如何每小时执行一次任务?

1 个答案:

答案 0 :(得分:0)

Foreach应该在调度程序中完成,看一下代码

app/console/kernel

    namespace App\Console;

    use DB;
    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

    class Kernel extends ConsoleKernel
    {
        /**
         * The Artisan commands provided by your application.
         *
         * @var array
         */
        protected $commands = [
            //
        ];

        /**
         * Define the application's command schedule.
         *
         * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
         * @return void
         */
        protected function schedule(Schedule $schedule)
        {
            $schedule->call(function () {
                foreach ($tasks as $task) {
                    $schedule->command(TaskCommand::class, [$task->id]);
                }
            })->hourly();
        }
    }

然后您需要通过以下命令在服务器上将其切换:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

更多:https://laravel.com/docs/5.6/scheduling

祝你好运!