laravel 的任务调度,默认在 App\Console\Kernel 类 的schedule 中

三种调度 计划方式:

  1. 闭包形式 : call protected function schedule(Schedule $schedule){ $schedule->call(function () { //自定义逻辑处理 })->daily(); //调度频率 }
  2. artisan 命令 或者 系统命令 : $schedule->command('emails:send --force')->daily();
  3. command 类 :command $schedule->command(Command::class, ['--force'])->daily();
    command 类 需要在 App\Console\Kernel 中注册 protected $commands = [ \App\Console\Commands\Inspire::class, ];

$schedule->exec('node /home/forge/script.js')->daily(); //可以将命令发送到系统

调度频率设置

->cron('* * * * *')     自定义调度任务
->everyMinute(); 	 每分钟执行一次任务
->everyFiveMinutes(); 	每五分钟执行一次任务
->everyTenMinutes(); 	每十分钟执行一次任务
->everyThirtyMinutes(); 	每半小时执行一次任务
->hourly(); 	每小时执行一次任务
->hourlyAt(17); 	每一个小时的第 17 分钟运行一次
->daily(); 	每到午夜执行一次任务
->dailyAt('13:00'); 	每天的 13:00 执行一次任务
->twiceDaily(1, 13); 	每天的 1:00 和 13:00 分别执行一次任务
->weekly(); 	每周执行一次任务
->monthly(); 	每月执行一次任务
->monthlyOn(4, '15:00'); 	在每个月的第四天的 15:00 执行一次任务
->quarterly(); 	每季度执行一次任务
->yearly(); 	每年执行一次任务
->timezone('America/New_York'); 	设置时区

额外限制条件

->weekdays(); 	限制任务在工作日
->sundays(); 	限制任务在星期日
->mondays(); 	限制任务在星期一
->tuesdays(); 	限制任务在星期二
->wednesdays(); 	限制任务在星期三
->thursdays(); 	限制任务在星期四
->fridays(); 	限制任务在星期五
->saturdays(); 	限制任务在星期六
->between($start, $end); 	限制任务运行在开始到结束时间范围内
->unlessBetween($start,$end)
->when(Closure); 	限制任务基于一个为真的验证,传递一个闭包,返回真会继续执行
->skip(Closoure);  返回真,停止执行

避免重复任务

->withoutOverlapping();

强制维护模式下也运行

->evenInMaintenanceMode();
 ->sendOutputTo($filePath);   //输出任务到文件
 ->appendOutputTo($filePath);  //添加到文件
发送到邮件
$schedule->command('foo')
         ->daily()
         ->sendOutputTo($filePath)   //必须要这个
         ->emailOutputTo('foo@example.com');  

任务钩子

->before(Clousoure function(){   });
->after(Clousoure function(){   });

ping

->pingBefore($url);
->thenPing($url);
需要扩展包支持
composer require guzzlehttp/guzzle

一次性启动任务: 常用于测试

php artisan schedule:run   //运行所有任务

定时调度

crontab -e
	* * * * * php  programPath/artisan schedule:run  >> /dev/null 2>&1

总结:可在 command 类的 handle 方法中调用service 服务