关于laravel5.5的定时任务详解(demo)(2)

4、我的kernel.php文件

<?php
//此处省略了命名空间部分
class Kernel extends ConsoleKernel
{
 /**
 * The Artisan commands provided by your application.
 *注:此处是引入我们新创建的类。由于我们此处是使用命令名来操作的,所以没用上这个类名。不过还是引入比较标准
 * 可以使用 command 方法通过命令名或类来调度一个 Artisan 命令:
 * $schedule->command('emails:send --force')->daily();
 * $schedule->command(EmailsCommand::class, ['--force'])->daily();
 *
 * @var array
 */
 protected $commands = [
 Test::class,
 CalculateData::class,
 UpdateOffset::class,
 ];

 /**
 * Define the application's command schedule.
 * 注:
 * 1、这个方法按照自己的需求,确定定时方法的执行顺序。通过after,before等关键词来控制
 * 2、此处相当于规定同意的定时执行时间,如都在0:30分执行下面的几个定时任务
 * @param \Illuminate\Console\Scheduling\Schedule $schedule
 * @return void
 */
 protected function schedule(Schedule $schedule)
 {
 // 每天凌晨 0.45 执行同步 aliyun 数据的任务,并发送邮件给 ***
  $schedule->command('iot:sync Flow')
  ->after(function() {
   //更新偏移量,after里面不能加参数
  Artisan::call('Test:data');
  })
  ->after(function () {
  // 执行同步数据命令完成后 则执行计算数据任务
  Artisan::call('calculate:data');
  });
 }

 /**
 * Register the commands for the application.
 * //这个部分是laravel自动生成的,引入我们生成的命令文件
 * @return void
 */
 protected function commands()
 {
 $this->load(__DIR__.'/Commands');

 require base_path('routes/console.php');
 }
}

关于具体的调度方法schedule(),大家可以去laravel文档看看,里面可以规定很多东西。我这边是使用的钩子函数。在同时要执行多个定时任务的时候,通过after,before等方法,可以让多个定时任务变得有序起来。

三、执行我们的定时

虽然laravel的定时任务一直都说的很强大,但本质上还是离不开服务器上的cron脚本。。

1、先查看服务器上的定时条目

crontab -l

2、新增或编辑cron 条目

crontab -e

3、在里面新增我们写好的方法路径

这里面新加上我们的定时任务。

第一是 规定定时任务的执行时间

第二是 要把项目的artisan目录路径写对

第三 schedule:run就是执行咱们之前写的任务调度,也就是kernel.php文件中的schedule方法。

如果是大家自己测试的话,可以随便写个定时任务,每分钟执行以下,这样就能准确的知道自己的定时任务是否正确了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3825.html