天天看点

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

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

任务调度写在  

app/Console/Kernel.

PHP

 文件 

schedule 

中,里面默认有一个例子。在 schedule 方法里放入自己的执行的代码。比如

这个是每一分钟在

数据库

里插入一条数据。

[html] 

  1. <?php  
  2. namespace App\Console;  
  3. use Illuminate\Console\Scheduling\Schedule;  
  4. use Illuminate\Foundation\Console\Kernel as ConsoleKernel;  
  5. use Illuminate\Support\Facades\DB;  
  6. class Kernel extends ConsoleKernel  
  7. {  
  8.     /**  
  9.      * The Artisan commands provided by your application.  
  10.      *  
  11.      * @var array  
  12.      */  
  13.     protected $commands = [  
  14.         \App\Console\Commands\Inspire::class,  
  15.     ];  
  16.      * Define the application's command schedule.  
  17.      * @param  \Illuminate\Console\Scheduling\Schedule  $schedule  
  18.      * @return void  
  19.     protected function schedule(Schedule $schedule)  
  20.     {  
  21.         $schedule->exec(  
  22.             $schedule->call(function () {  
  23.                 DB::table('ceshi')->insert(['contents'=>'新的数据']);  
  24.             })->everyMinute()  
  25.         )->daily();  
  26.     }  
  27. }  

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

借助Liunx的crontab  来定时执行

执行,crontab -e 

此时显示

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

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

在最下面写入 

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