[英]how to change laravel jobs time
我正在為客戶開發應用程序,他想在特殊時間開始一些工作,我必須在工作中運行它,對嗎? 例如,他想發布一個帖子有 2 個狀態已發布或等待並在發送頁面,他可以設置發布帖子的時間我如何在工作中開發這個?
ScanJob::dispatch($property->Name, $property->Owner, $Scan->id)->delay(Carbon::now()->addHour(Carbon::now()->diffInHours($Time)));
這是我第一次嘗試以小時為單位獲取差異時間並從延遲中添加它
基本上有兩種方法可以解決您的問題:
創建一個 Laravel Artisan 命令(您也可以使用 Laravel 提供的其他方法,但我發現 Artisan 更有趣且更靈活,有助於避免返工)並相應地安排它。
創建一個排隊作業並在稍后調度它,但它有一些限制,例如,Amazon SQS 隊列服務的最大延遲時間為 15 分鍾。
現在,要做什么:
現在是有趣的部分。 注意:您不必擔心,Laravel 將為您執行大部分步驟。 為了不跳過知識,我提到了每一步。
第 1 步:運行以下命令以創建 Artisan 控制台命令(請記住位於項目的根路徑中。):
php artisan make:command PublishSomething
該命令現在可用於app/Console/Commands
的進一步開發。
第 2 步:您將在 Class 中看到一個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 步:我們的 function 運行良好。 現在我們將安排命令。 在app/Console
中你會找到一個文件Console.php
,在我們的例子中,這個 class 負責所有的任務調度注冊。
<?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');
}
}
注意這里的計划 function,這是我們將添加計划邏輯的地方。
第 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 分鍾一次。
您可以了解有關Laravel Artisan 命令和Laravel 任務調度的更多信息。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.