一、首先添加Crontab定时任务,这里只做大略先容:
用命令crontab -e 添加如下内容
/usr/local/bin/php /usr/local/var/www/projectName/artisan schedule:run >> /dev/null 2>&1
如图:

上面命令Crontab会每分钟去调Laravel的schedule命令,然后Laravel判断实行任务。
把稳:要把稳php和artisan的目录,which php可以查看php目录
你的命令
其余上面的命令前面的5个分别代表分钟、小时、天、月、星期。
分钟:0-59的整数,默认和/1 代表1分钟。小时:0-23的整数。天:1-31的整数。月:1-12的整数。星期:0-7的整数,0和7都代表星期日。crontab -l 可以列出当前的定时任务。二、添加Laravel调度任务:
1、在App\Console\Kernel类中定义你的调度任务:
<?phpnamespace App\Console;use Illuminate\Console\Scheduling\Schedule;use Laravel\Lumen\Console\Kernel as ConsoleKernel;use Log;class Kernel extends ConsoleKernel{ / The Artisan commands provided by your application. 定义Artisan命令 @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->call(function () {// Log::info('任务调度');// })->everyMinute(); //方法二: $schedule->command('test')->everyMinute(); }}
上面举例了两种实现方法,方法一是用闭包,方法二是用Artisan命令实现的。
调度的韶光可以有多种:
->cron(‘ ’); 在自定义Cron调度上运行任务->everyMinute(); 每分钟运行一次任务->everyFiveMinutes(); 每五分钟运行一次任务->everyTenMinutes(); 每十分钟运行一次任务->everyThirtyMinutes(); 每三十分钟运行一次任务->hourly(); 每小时运行一次任务->daily(); 每天凌晨零点运行任务->dailyAt(‘13:00’); 每天13:00运行任务->twiceDaily(1, 13); 每天1:00 & 13:00运行任务->weekly(); 每周运行一次任务->monthly(); 每月运行一次任务
还有一下额外的方法,请参考:http://laravelacademy.org/post/235.html
下面连续方法二的操作:
三、定义Artisan命令的方法:
<?php namespace App\Console\Commands;use Illuminate\Console\Command;use Log;class test extends Command { / The console command name. @var string / protected $name = 'test:putcache'; / The console command description. @var string / protected $description = 'test controller'; / Execute the console command. @return mixed / public function handle(){ //这里做任务的详细处理,可以用模型 Log::info('任务调度'.time()); }}
好了,以上就可以实行定时任务了,有个小技巧如果上面的任务没实行可以用命令php artisan list 可以打印出一些缺点信息。