![](/img/trans.png)
[英]How can I Publish A Blog Posts In The Future On A Specific Date And TIme In Laravel
[英]How I can execute a command at a specific date and time in laravel 5.8?
Ι 需要能夠 rto 調度命令以在特定日期和時間運行。
我有以下世界末日核彈命令:
<?php
namespace App\Console\Commands;
class DommdayCommand extends Command
{
protected $signature='nuke:country {commander} {country} ';
protected $description="Nuke a country";
public function handle()
{
$dictator= $this->argument('commander');
$country= $this->argument('country');
$this->output("Nuking the {$country} from {$dictator} ");
}
}
我有一個具體的時間表:
Kim Young Un will nuke Amerika at 2021-06-12 13:00
Osama Bin laden's clone will nuke Amerika at 2021-06-15 18:00
Adolf Hitler's clone will nuke Israel at 2021-06-15 06:00
...
那么我如何編寫特定日期的時間表,在特定的日期和時間只執行一次特定的命令呢? 現有文檔允許我安排將在特定日期和時間連續執行的命令,例如每小時或每天。
那么我如何指定將要執行的特定日期。
現有的cron()
function 允許我控制小時、分鍾、月、日和星期幾的執行。 但它不允許我指定執行年份。 就我而言,執行年份也很重要。 (我們不希望從特定指揮官那里重新對一個已經擁有核武器的國家進行核打擊,明年也同樣不可行)。
例如,如果我在Kernel.php
中指定以下內容:
$schedule->command(DommdayCommand::class)->cron('13 00 15 02 *')
將在 2021-02-15 2021-02-15 13:00
執行命令,但也將在2022-02-15 13:00
執行命令,我不想這樣做。 我只想在2021-02-15 13:00
被處決,永遠不再被處決。
根據文檔,您可以使用 cron 檢查:
根據控制台命令執行。 盡管它可能會導致您在 cron 上指定的每個月日期 hout 和 minut 運行,但您可以調用閉包,如本文檔所示。 因此,您可以在Kernel.php
處使用閉包。
use Carbon\Carbon;
use Illuminate\Support\Facades\Artisan
class Kernel extends ConsoleKernel
{
// Sopme code exists here
protected function schedule(Schedule $schedule): void
{
// Rest of schedules
$schedule->call(function () {
$year = Carbon::now()->y;
if($year == 2021){
Artisan::call('nuke:country "Kim Young Un" Amerika');
}
})->cron('13 00 12 06 *');
// More schedules
}
// Rest of code here
}
因此,使用閉包檢查年份,然后如果年份是合適的年份,則在 cron 表達式上調用代碼,檢查執行的月、日、小時和分鍾。
另一種方法是讓閉包處理這一切:
$schedule->call(function () {
$dates=[
'2021-06-12 13:00' => [
'commander'=>'Kim Young Un',
'country' => 'America'
],
'2021-06-15 18:00' => [
'commander'=>'Osama Bin Laden's clone',
'country' => 'America'
],
'2021-06-15 06:00' => [
'commander'=>'Adolf Hitler's clone',
'country' => 'Israel'
],
];
$date = Carbon::now()->format('Y-m-d H:i:s');
if(isset($dates[$date])){
$params=$dates[$date];
Artisan::call("nuke:country \"{$params['commander']}\" {$params['country']}");
}
})->cron('*****');
換句話說,在適當的日期執行命令並不斷檢查執行日期是否合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.