首先进入你的 Laravel 项目目录
然后创建一个 Hello.php 测试任务
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 = 'test';//命令名称,待会调用php artisan test就会执行 /** * 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() { //逻辑处理代码放这 echo 'Hello World'; } }
代码里我加了些注释,方便大家理解。
定时脚本写好后,需要注册这个任务。在 Commands 同级有个 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 = [ //注册 Test Commands\Test::class ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // 每分钟跑一次 $schedule->command('test')->everyMinute(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
当你注册了 test 脚本后,就可以在终端测试运行
php artisan test
同时,你需要在服务器添加个定时任务
* * * * * php /www/wwwroot/laravel57/artisan schedule:run
这样你的脚本就能定时每分钟跑一次了。
你也可以在 schedule 方法中,自定义执行间隔,时间设置方法有下面这些:
->between($startTime, $endTime) 任务在startTime和endTime时间段之内被调用,example:->between(8:00,9:00)表示8:00到9:00之间调用任务
->unlessbetween($startTime, $endTime) 任务在startTime和endTime时间段之内不被调用,example:->between(8:00,9:00)表示8:00到9:00之间不调用任务
->inTimeInterval($startTime, $endTime) 同between($startTime, $endTime),因为between()最终还是去调用了inTimeInterval()这个函数
->everyMinute() 最简单的一个函数,每分钟调用一次
->everyFiveMinutes() 每5分钟调用一次
->everyTenMinutes() 每10分钟调用一次
->everyFifteenMinutes() 每15分钟调用一次
->everyThirtyMinutes() 每30分钟调用一次
->hourly() 每小时调用一次,准点调用
->hourlyAt($offset) 每小时调用一次,example: ->hourly(30) 1:30,2:30,3:30...调用一次
->daily() 每天0:00调用一次
->dailyAt($time) example: ->daily(9:00)每天9点调用一次
->at($time) 在给定的时间调用函数
->twiceDaily($first = 1, $second = 13) 每天调用两次,默认0点和12点调用
->weekdays() 工作日调用
->weekends() 周末调用
->mondays() 周一调用
->tuesdays() 周二调用
->wednesdays() 周三掉用
->thursdays() 周四调用
->firdays() 周五调用
->saturdays() 周六调用
->sundays() 周日调用
->weekly() 每周调用一次
->weeklyOn($day, $time = '0:0') example: ->weeklyOn(0, 8:00)每周日8点调用,0,7都表示周日,1-6,相对应
->monthly() 每月调用一次
->monthlyOn($day, $time = '0:0') emaple: ->monthlyOn(5, 9:00) 每月5号9:00调用
->twiceMonthly($first = 1, $second = 16) 每月调用2次,如果没理解错应该是默认每月1号零点和16号零点(15号24点),没测试
->quarterly() 每季度调用一次
->yearly() 每年调用一次