php artisan make:command
{脚本名称} 生成执行文件,文件在 app/Console/Commands
中查看。protected $signature = 'stat:generate {start? : 脚本统计的起始时间(选填 eg.2017-10-01 )} {end? : 脚本统计的结束时间(选填)}'; protected $description = '生成每日的统计信息';
$signature属性中的 start? end? 表示可输入的可选参数,这里提供了脚本开始和结束时间的可选项,用于生成指定时间日期内的统计信息,eg. php artisan stat:generate 2017-08-01 。php
public function handle() { // 若是未输入日期参数,默认选择前一天做为统计时间(??是php7新语法) $this->date = $this->argument('start') ?? date('Y-m-d', strtotime('-1 day')); $endDate = $this->argument('end') ?? date('Y-m-d'); // 判断输入的日期格式是否正确 if (!strtotime($this->date) || !strtotime($endDate)) { $this->error('请输入正确的日期格式!');die; } // 循环执行每一天的统计脚本 while ($this->date < $endDate) { // 这里是须要执行的统计逻辑,sql等 $this->_active_num_game(); // 每执行一次,统计日期加1天 $this->date = date('Y-m-d', strtotime("{$this->date} +1 day")); } }
将如下命令添加到cron 中laravel
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
全部的计划任务定义在 AppConsoleKernel 类的 schedule 方法中,Artisan命令写在commands属性中。sql
protect $commands = [ Commands\{声明的脚本文件名称}::class ]; protected function schedule(Schedule $schedule) { // 上面的Artisan命令将在每晚执行 $schedule->command('stat:generate')->daily(); }