laravel 任务调度(定时执行任务)


任务调度写在  app/Console/Kernel.PHP 文件 schedule 中,里面默认有一个例子。在 schedule 方法里放入自己的执行的代码。比如

这个是每一分钟在数据库里插入一条数据。

[html] 

  1. <?php  

  2.   

  3. namespace App\Console;  

  4.   

  5. use Illuminate\Console\Scheduling\Schedule;  

  6. use Illuminate\Foundation\Console\Kernel as ConsoleKernel;  

  7. use Illuminate\Support\Facades\DB;  

  8.   

  9. class Kernel extends ConsoleKernel  

  10. {  

  11.     /**  

  12.      * The Artisan commands provided by your application.  

  13.      *  

  14.      * @var array  

  15.      */  

  16.     protected $commands = [  

  17.         \App\Console\Commands\Inspire::class,  

  18.     ];  

  19.   

  20.     /**  

  21.      * Define the application's command schedule.  

  22.      *  

  23.      * @param  \Illuminate\Console\Scheduling\Schedule  $schedule  

  24.      * @return void  

  25.      */  

  26.     protected function schedule(Schedule $schedule)  

  27.     {  

  28.   

  29.         $schedule->exec(  

  30.             $schedule->call(function () {  

  31.                 DB::table('ceshi')->insert(['contents'=>'新的数据']);  

  32.             })->everyMinute()  

  33.         )->daily();  

  34.     }  

  35. }  


写完了,还需要定时执行怎么办?

借助Liunx的crontab  来定时执行

执行,crontab -e 

此时显示


出现这样的界面,就是进入crontab里面了,接着

在最下面写入 

* * * * * php 项目的路径/artisan schedule:run >> /dev/null 2>&1
按下 Ctrl + X 保存退出
这样就OK ,如果不执行,请下检查代码,以及项目的路径是否正确。