基于Laravel框架定时任务相关实现方法及操作注意事项

2019-01-24 09:42:27 来源:互联网作者:hello_sgw 人气: 次阅读 555 条评论

Laravel框架定时任务2种实现方式,结合实例形式较为详细的分析了Laravel框架定时任务相关实现方法及操作注意事项,需要的朋友可以参考下。...

  文章主要介绍了Laravel框架定时任务2种实现方式,结合实例形式较为详细的分析了Laravel框架定时任务相关实现方法及操作注意事项,需要的朋友可以参考下。

  Laravel框架定时任务2种实现方式,具体如下:

第一种

  1、生成一个commands文件?

> php artisan make:command test

  2、打开文件进行修改

  laravel\App\Console\Commands\test.php

  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Log;
  5. class test extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'test:insert'; // php artisan list 中将会生成 "php artisan test:insert " 指令
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'insert Test table some test data'; // 对上面指令的描述
  19. /**
  20. * Create a new command instance.
  21. *
  22. * @return void
  23. */
  24. public function __construct()
  25. {
  26. parent::__construct();
  27. }
  28. /**
  29. * Execute the console command.
  30. *
  31. * @return mixed
  32. */
  33. public function handle()
  34. {
  35. // 编写你要的定时任务执行的代码!
  36. # eg
  37. Log::info('test');
  38. }
  39. }

  > php artisan list查看

  3、然后修改:laravel\app\Console\Kernel.php文件?

  1. <?php
  2. namespace App\Console;
  3. use Illuminate\Console\Scheduling\Schedule;
  4. use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
  5. class Kernel extends ConsoleKernel
  6. {
  7. protected $commands = [
  8. // 参考手册 新加
  9. \App\Console\Commands\test::class,
  10. ];
  11. // 定义应用的命令调度
  12. protected function schedule(Schedule $schedule)
  13. {
  14. // 新加 每分钟执行一次
  15. $schedule->command('test:insert')->everyMinute();
  16. }
  17. protected function commands()
  18. {
  19. $this->load(__DIR__.'/Commands');
  20. require base_path('routes/console.php');
  21. }
  22. }

  4、启用计划任务:在服务器中加入到计划任务crontab -e

  注意这里的 path 是你的laravel项目根目录的 绝对路径!, 然后加上后面的 artisan 到结尾的字符串

* * * * * php /path/artisan schedule:run >> /dev/null 2>&1

* * * * * php /code/src/laravel/artisan schedule:run >> /dev/null 2>&1

  5、打开日志文件查看

  laravel\storage\logs\laravel.log

第二种

  使用 shell脚本执行

  因为php artisan list可以查看到 执行指令test:insert

  所以可以考虑用 .sh 脚本执行,还是类似上面crontab -e编写

  1、先编写 .sh 脚本laravel/test.sh放在项目某个位置,文件内写入?

php artisan test:insert

  上面指令在命令行手动每执行一次就可以触发一次编写的程序,相当于给 laravel.log 写入一次 test

  2、使用crontab -e编写 执行 第一步写的 test.sh 脚本

  * * * * * laravel/test.sh

  以上两种均可看到 laravel.log 日志

  希望Laravel框架定时任务2种实现方式示例所述对大家基于Laravel框架的PHP程序设计有所帮助。

您可能感兴趣的文章

    无相关信息

相关文章