使用命令创建任务
php artisan make:command test
命令执行成功后会在项目app\Console\Commands目录下面生成 test.php文件,内容如下
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class test extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; // 此处代表laravel自动生成的名称,下面执行的时候能用到 /** * The console command description. * * @var string */ protected $description = 'Command description'; // 任务描述,作用不大 /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // 任务逻辑 } }
编辑 signature、description 属性,增加阅读性
protected $signature = 'demo'; protected $description = 'laravel5.5定时任务实例';
编辑业务逻辑,这里只做演示 在test表中添加一条日期数据
public function handle() { DB::table('test')->insert([ 'date' => date('Y-m-d H:i:s'), ]); }
编辑项目app\Console\目录下Kernel.php
<?php namespace App\Console; 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 = [ \App\Console\Commands\test::class, // 添加任务类 ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); $schedule->command('demo')->everyMinute(); // 设置任务每分钟运行一次 } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
开启lavavel任务调度器(重点)
* * * * * php /path to project/artisan schedule:run >> /dev/null 2>&1
该cron会每分钟调用一次 laravel 命令调度器,然后laravel 会自动评估你的调度任务并运行到期的任务
其中 path to project 为实际项目地址
修改cron为实际项目地址
* * * * * php /home/vagrant/code/artisan schedule:run >> /dev/null 2>&1
至此定时任务配置完成,实际运行效果如下
系统每分钟会执行一次laravel调度器,而laeravel则会分析Kernel.php中定义的任务规则执行到期的任务