laravel 定时任务 5.2
2018年5月7日官方文档给出的教程已经很详细了,这里给出一些补充帮助大家理解。
英文文档:https://laravel.com/docs/5.2/scheduling
中文文档:https://laravel-china.org/docs/5.2/scheduling
Starting The Scheduler
这里文档说的很简单,就是让你在服务器的crontab加入一条命令。
1 |
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1 |
关于crontab可以参考这篇文章:http://www.cnblogs.com/xxoome/p/6091459.html
这条命令什么意思呢?按照crontab配置文件格式的解释
红框内都是shell命令。
##如果配有配置php的全局环境变量,这里需要指定php的绝对路径。
php:/usr/local/php/bin/php
##就是你项目根目录下的artisan文件的绝对路径
artisan:/home/prj-test/test/artisan
例如:
1 |
* * * * * /usr/local/php/bin/php /home/prj-test/test/artisan schedule:run >> /dev/null 2>&1 |
1、创建artisan命令行
文档地址:https://laravel-china.org/docs/5.2/artisan
1 |
php artisan make:console TestConsole |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class TestConsole extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'testconsole'; /** * The console command description. * * @var string */ protected $description = '这是一个测试artisan的描述'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { Log::info('这是我写的log'); } } |
2、编写Kernel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Support\Facades\Log; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // Commands\Inspire::class, Commands\TestConsole::class ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); Log::info('zddddd'); //调用artisan $schedule->command('testconsole')->everyMinute(); } } |