溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Laravel框架實(shí)現(xiàn)定時(shí)任務(wù)

發(fā)布時(shí)間:2021-04-13 16:50:21 來(lái)源:億速云 閱讀:264 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

如何使用Laravel框架實(shí)現(xiàn)定時(shí)任務(wù)?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

第一種

1、生成一個(gè)commands文件

> php artisan make:command test

2、打開(kāi)文件進(jìn)行修改

laravel\App\Console\Commands\test.php

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class test extends Command
{
 /**
  * The name and signature of the console command.
  *
  * @var string
  */
 protected $signature = 'test:insert'; // php artisan list 中將會(huì)生成 "php artisan test:insert " 指令
 /**
  * The console command description.
  *
  * @var string
  */
 protected $description = 'insert Test table some test data'; // 對(duì)上面指令的描述
 /**
  * Create a new command instance.
  *
  * @return void
  */
 public function __construct()
 {
  parent::__construct();
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
  // 編寫你要的定時(shí)任務(wù)執(zhí)行的代碼!
  # eg
 Log::info('test');
 }
}

> php artisan list 查看

如何使用Laravel框架實(shí)現(xiàn)定時(shí)任務(wù)

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

<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
 protected $commands = [
  // 參考手冊(cè) 新加
  \App\Console\Commands\test::class,
 ];
 // 定義應(yīng)用的命令調(diào)度
 protected function schedule(Schedule $schedule)
 {
   // 新加 每分鐘執(zhí)行一次
  $schedule->command('test:insert')->everyMinute();
 }
 protected function commands()
 {
  $this->load(__DIR__.'/Commands');
  require base_path('routes/console.php');
 }
}

4、啟用計(jì)劃任務(wù):在服務(wù)器中加入到計(jì)劃任務(wù) crontab -e

注意這里的 path 是你的laravel項(xiàng)目根目錄的 絕對(duì)路徑!, 然后加上后面的 artisan 到結(jié)尾的字符串

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

5、打開(kāi)日志文件查看

laravel\storage\logs\laravel.log

第二種

使用 shell腳本執(zhí)行

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

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

1、先編寫 .sh 腳本 laravel/test.sh 放在項(xiàng)目某個(gè)位置,文件內(nèi)寫入

php artisan test:insert

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

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

* * * * * laravel/test.sh

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

如何使用Laravel框架實(shí)現(xiàn)定時(shí)任務(wù)

關(guān)于如何使用Laravel框架實(shí)現(xiàn)定時(shí)任務(wù)問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI