1 回答

TA貢獻1821條經驗 獲得超5個贊
基本上有兩種方法可以解決您的問題:
創建一個 Laravel Artisan 命令(您也可以使用 Laravel 提供的其他方法,但我發現 Artisan 更有趣且更靈活,有助于避免返工)并相應地安排它。
創建一個隊列作業并在稍后派發它,但它有一些限制,例如 Amazon SQS 隊列服務的最大延遲時間為 15 分鐘。
現在,要做的是:
在我看來,您應該使用解決方案 1,因為它更靈活并且給您更多的控制權。
隊列用于兩件事。首先,理想情況下,您要執行的任務應在接下來的 30-45 分鐘內完成。其次,任務是時間密集型的,您不想因此而阻塞線程。
現在是有趣的部分。注意:您不必擔心,Laravel 會為您執行大部分步驟。為了不跳過知識,我提到了每一步。
第 1 步:運行以下命令創建一個 Artisan 控制臺命令(記住要在項目的根路徑中。):
php?artisan?make:command?PublishSomething
該命令現在可用于進一步開發,網址為app/Console/Commands
。
第 2 步handle
:您將在類中看到一個方法,如下所示,這是您所有邏輯所在的地方。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class PublishSomething extends Command
{
? ? /**
? ? ?* The name and signature of the console command.
? ? ?*
? ? ?* @var string
? ? ?*/
? ? protected $signature = 'something:publish';
? ? /**
? ? ?* The console command description.
? ? ?*
? ? ?* @var string
? ? ?*/
? ? protected $description = 'Publishes something amazing!';
? ? /**
? ? ?* Create a new command instance.
? ? ?*
? ? ?* @return void
? ? ?*/
? ? public function __construct()
? ? {
? ? ? ? parent::__construct();
? ? }
? ? /**
? ? ?* Execute the console command.
? ? ?*
? ? ?* @return mixed
? ? ?*/
? ? public function handle()
? ? {
? ? ? ? //
? ? }
}
第 3 步:讓我們在 handle 方法中添加一些邏輯
/**
?* Execute the console command.
?*
?* @return mixed
?*/
public function handle()
{
? ? $this->info('Publishing something cool!');
? ? // you can add your own custom logic here.
}
第 4 步:添加邏輯后,現在我們需要對其進行測試,您可以這樣做:
php artisan something:publish
第 5 步:我們的功能運行正?!,F在我們將安排命令。在里面app/Console你會發現一個文件Console.php,這個類負責所有的任務調度注冊,在我們的例子中。
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
? ? /**
? ? ?* The Artisan commands provided by your application.
? ? ?*
? ? ?* @var array
? ? ?*/
? ? protected $commands = [
? ? ? ? //
? ? ];
? ? /**
? ? ?* Define the application's command schedule.
? ? ?*
? ? ?* @param? \Illuminate\Console\Scheduling\Schedule? $schedule
? ? ?* @return void
? ? ?*/
? ? protected function schedule(Schedule $schedule)
? ? {
? ? ? ? // $schedule->command('inspire')->hourly();
? ? }
? ? /**
? ? ?* Register the commands for the application.
? ? ?*
? ? ?* @return void
? ? ?*/
? ? protected function commands()
? ? {
? ? ? ? $this->load(__DIR__.'/Commands');
? ? ? ? require base_path('routes/console.php');
? ? }
}
注意這里的調度函數,這是我們將添加調度邏輯的地方。
第 6 步:現在我們將安排我們的命令每 5 分鐘運行一次。你可以很容易地改變時間段,Laravel 提供了一些預制的頻率選項,你也有自己的自定義時間表。
/**
?* Define the application's command schedule.
?*
?* @param? \Illuminate\Console\Scheduling\Schedule? $schedule
?* @return void
?*/
protected function schedule(Schedule $schedule)
{
? ? $schedule->command('something:publish')->everyFiveMinutes(); // our schedule
}
第 7 步:現在,Laravel 的任務調度程序本身依賴于 Cron。因此,要啟動計劃,我們將以下文件添加到我們的 crontab。
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
就是這樣!我們完了。您已經創建了自己的自定義命令并計劃每 5 分鐘執行一次。
- 1 回答
- 0 關注
- 155 瀏覽
添加回答
舉報