应用场景:定时脚本任务需要清晨计算前一天的数据,汇总成统计表。Artisan命令复杂的计时任务可以与Artisan命令结合使用。Artisan命令:按照LaravelArtisan命令行文档了解其用法和配置。使用Artisan命令phpartisanmake:command{scriptname}生成执行文件,在app/Console/Commands中可以查看到该文件。添加Artisan命令的名称和描述,例如:protected$signature='stat:generate{start?:脚本统计的开始时间(optionaleg.2017-10-01)}{end?:脚本统计结束时间(可选)}';protected$description='生成每日统计信息';开始?在指定的时间和日期内生成统计信息,例如。phpartisan统计:生成2017-08-01。在handle()方法中编写程序部分publicfunctionhandle(){//如果不输入日期参数??,则默认选择前一天作为统计时间(??是php7的新语法)$this->date=$this->argument('开始')??date('Y-m-d',strtotime('-1天'));$endDate=$this->argument('end')??日期('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}+1day"));}}定时脚本任务:在cron中加入如下命令*****php/path-to-your-project/artisanschedule:run>>/dev/null2>&1所有的定时任务都定义在schedule的方法中AppConsoleKernel类和Artisan命令都写在commands属性中。protect$commands=[Commands\{声明的脚本文件名}::class];protectedfunctionschedule(Schedule$schedule){//上面的Artisan命令将在每晚执行$schedule->command('stat:generate')->daily();}
