定時(shí)調(diào)用 Artisan 命令

2018-02-24 15:53 更新

過去,開發(fā)者會(huì)對每個(gè)他們想要調(diào)用的命令行指令建立 Cron 對象。然而,這很令人頭痛。你的命令行指令調(diào)用不再包含在版本控制里面,并且你必須 SSH 進(jìn)入你的服務(wù)器以添加 Cron 對象。讓我們來讓生活變得更輕松。Laravel 命令調(diào)用器允許你順暢地且語義化地定義命令調(diào)用在 Laravel 里面,而且你的服務(wù)器只需要一個(gè) Cron 對象。

你的命令調(diào)用保存在 app/Console/Kernel.php 文件。你會(huì)在這個(gè)類里看到一個(gè) schedule 方法。為了幫助您開始,方法里面包含一個(gè)簡單的例子。你可以依照你需要的自由地添加任何數(shù)量的預(yù)定工作到 Schedule 對象。你只需要添加這個(gè) Cron 對象到服務(wù)器:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

這個(gè) Cron 將會(huì)每分鐘調(diào)用 Laravel 命令調(diào)用器。接著,Laravel 評估你的預(yù)定工作并在時(shí)間到時(shí)執(zhí)行工作。這不能再更簡單了!

更多調(diào)用的例子

讓我們來多看幾個(gè)調(diào)用的例子:

調(diào)用閉包

$schedule->call(function()
{
    // 執(zhí)行一些任務(wù)...

})->hourly();

調(diào)用終端機(jī)命令

$schedule->exec('composer self-update')->daily();

自己配置 Cron 表達(dá)式

$schedule->command('foo')->cron('* * * * *');

頻繁的工作

$schedule->command('foo')->everyFiveMinutes();

$schedule->command('foo')->everyTenMinutes();

$schedule->command('foo')->everyThirtyMinutes();

每天一次的工作

$schedule->command('foo')->daily();

每天一次在特定時(shí)間 (24 小時(shí)制) 的工作

$schedule->command('foo')->dailyAt('15:00');

每天兩次的工作

$schedule->command('foo')->twiceDaily();

每個(gè)工作日執(zhí)行的工作

$schedule->command('foo')->weekdays();

每周一次的工作

$schedule->command('foo')->weekly();

// 調(diào)用每周一次在特定的日子 (0-6) 和時(shí)間的工作...
$schedule->command('foo')->weeklyOn(1, '8:00');

每月一次的工作

$schedule->command('foo')->monthly();

特定日期的工作

$schedule->command('foo')->mondays();
$schedule->command('foo')->tuesdays();
$schedule->command('foo')->wednesdays();
$schedule->command('foo')->thursdays();
$schedule->command('foo')->fridays();
$schedule->command('foo')->saturdays();
$schedule->command('foo')->sundays();

Prevent Jobs From Overlapping

By default, scheduled jobs will be run even if the previous instance of the job is still running. To prevent this, you may use the withoutOverlapping method:

$schedule->command('foo')->withoutOverlapping();

In this example, the foo command will be run every minute if it is not already running.

限制應(yīng)該執(zhí)行工作的環(huán)境

$schedule->command('foo')->monthly()->environments('production');

指定工作在當(dāng)應(yīng)用程序處于維護(hù)模式也應(yīng)該執(zhí)行

$schedule->command('foo')->monthly()->evenInMaintenanceMode();

只允許工作在閉包返回 true 的時(shí)候執(zhí)行

$schedule->command('foo')->monthly()->when(function()
{
    return true;
});

將預(yù)定工作的輸出發(fā)送到指定的 E-mail

$schedule->command('foo')->sendOutputTo($filePath)->emailOutputTo('foo@example.com');

注意: 你必須先把輸出存到文件中才可以發(fā)送 email。

將預(yù)定工作的輸出發(fā)送到指定的路徑

$schedule->command('foo')->sendOutputTo($filePath);

在預(yù)定工作執(zhí)行之后 Ping 一個(gè)給定的 URL

$schedule->command('foo')->thenPing($url);
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)