基于Laravel框架定時任務相關實現(xiàn)方法及操作注意事項

2019-01-24 09:42:27 來源:互聯(lián)網作者:hello_sgw 人氣: 次閱讀 555 條評論

Laravel框架定時任務2種實現(xiàn)方式,結合實例形式較為詳細的分析了Laravel框架定時任務相關實現(xiàn)方法及操作注意事項,需要的朋友可以參考下。...

  文章主要介紹了Laravel框架定時任務2種實現(xiàn)方式,結合實例形式較為詳細的分析了Laravel框架定時任務相關實現(xiàn)方法及操作注意事項,需要的朋友可以參考下。

  Laravel框架定時任務2種實現(xiàn)方式,具體如下:

第一種

  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. // 編寫你要的定時任務執(zhí)行的代碼!
  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. // 新加 每分鐘執(zhí)行一次
  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腳本執(zhí)行

  因為php artisan list可以查看到 執(zhí)行指令test:insert

  所以可以考慮用 .sh 腳本執(zhí)行,還是類似上面crontab -e編寫

  1、先編寫 .sh 腳本laravel/test.sh放在項目某個位置,文件內寫入?

php artisan test:insert

  上面指令在命令行手動每執(zhí)行一次就可以觸發(fā)一次編寫的程序,相當于給 laravel.log 寫入一次 test

  2、使用crontab -e編寫 執(zhí)行 第一步寫的 test.sh 腳本

  * * * * * laravel/test.sh

  以上兩種均可看到 laravel.log 日志

  希望Laravel框架定時任務2種實現(xiàn)方式示例所述對大家基于Laravel框架的PHP程序設計有所幫助。

    無相關信息