剖析 Laravel 計劃任務--事件屬性

譯文GitHub https://github.com/yuansir/diving-laravel-zhphp

原文連接 https://divinglaravel.com/task-scheduling/properties-of-an-eventlaravel

Every entry you add is converted into an instance of Illuminate\Console\Scheduling\Event and stored in an $events class property of the Scheduler, an Event object consists of the following:git

你添加的每一個記錄都將轉換爲 Illuminate\Console\Scheduling\Event 的實例,並存儲在Scheduler的 $events 類屬性中,Event對象由如下內容組成:github

  • Command to run
  • CRON Expression
  • Timezone to be used to evaluate the time
  • Operating System User the command should run as
  • The list of Environments the command should run under
  • Maintenance mode configuration
  • Event Overlapping configuration
  • Command Foreground/Background running configuration
  • A list of checks to decide if the command should run or not
  • Configuration on how to handle the output
  • Callbacks to run after the command runs
  • Callbacks to run before the command runs
  • Description for the command
  • A unique Mutex for the command
  • 命令運行
  • CRON表達式
  • 用於評估時間的時區
  • 操做系統運行該命令的用戶
  • 命令應該運行的環境列表
  • 維護模式配置
  • 事件重疊配置
  • 命令前臺/後臺運行配置
  • 用於決定該命令是否運行的檢查列表
  • 如何處理輸出的配置
  • 命令運行後運行的回調
  • 在命令運行前運行的回調
  • 命令說明
  • 命令的惟一Mutex

The command to run could be one of the following:web

命令可能像下面一種方式運行:shell

  • A callback
  • A command to run on the operating system
  • An artisan command
  • A job to be dispatched
  • 回調
  • 在操做系統上運行的命令
  • artisan命令
  • 被調度的做業

Using a callback

使用回調

In case of a callback, the Container::call() method is used to run the value we pass which means we can pass a callable or a string representing a method on a class:express

在回調的狀況下,Container::call() 方法用於運行咱們傳遞的值,這意味着咱們能夠傳遞一個能夠調用或表示方法的字符串:數組

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
}

Or:app

protected function schedule(Schedule $schedule)
{
    $schedule->call('MetricsRepository@cleanRecentUsers')->daily();
}

Passing a command for the operating system

調用操做系統的命令

If you would like to pass a command for the operating system to run you can use exec():less

若是要運行操做系統的命令,可使用 exec()

$schedule->exec('php /home/sendmail.php --user=10 --attachInvoice')->monthly();

You can also pass the parameters as an array:

您還能夠將數組做爲參數:

$schedule->exec('php /home/sendmail.php', [
    '--user=10',
    '--subject' => 'Reminder',
    '--attachInvoice'
])->monthly();

Passing an artisan command

調用一個artisan命令

$schedule->command('mail:send --user=10')->monthly();

You can also pass the class name:

你也能夠傳一個類名

$schedule->command('App\Console\Commands\EmailCommand', ['user' => 10])->monthly();

The values you pass are converted under the hood to an actual shell command and passed to exec() to run it on the operating system.

你傳遞的值將轉換爲實際的shell命令,並傳遞給 exec() 在操做系統上運行。

Dispatching a Job

調度一個做業

You may dispatch a job to queue using the Job class name or an actual object:

您可使用Job類名稱或實際對象將做業分發到隊列中:

$schedule->job('App\Jobs\SendOffer')->monthly();

$schedule->job(new SendOffer(10))->monthly();

Under the hood Laravel will create a callback that calls the dispatch() helper method to dispatch your command.

Laravel會建立一個回調函數,調用 dispatch() 輔助方法來分發你的命令。

So the two actual methods of creating an event here is by calling exec() or call(), the first one submits an instance of Illuminate\Console\Scheduling\Event and the latter submits Illuminate\Console\Scheduling\CallbackEvent which has some special handling.

因此在這裏建立一個事件的兩個實際方法是經過調用 exec()call(),第一個提交一個 Illuminate\Console\Scheduling\Event 的實例,後者提交 Illuminate\Console\Scheduling\CallbackEvent來作一些特殊處理。

Building the cron expression

建立cron表達式

Using the timing method of the Scheduled Event, laravel builds a CRON expression for that event under the hood, by default the expression is set to run the command every minute:

使用計劃事件的計時方法,laravel會爲該事件建立一個CRON表達式,默認狀況下,表達式設置爲每分鐘運行一次命令:

* * * * * *

But when you call hourly() for example the expression will be updated to:

但當你調用 hourly() 時表達式會更新成這樣:

0 * * * * *

If you call dailyAt('13:30') for example the expression will be updated to:

當你調用 dailyAt('13:30') 時表達式會更新成這樣:

30 13 * * * *

If you call twiceDaily(5, 14) for example the expression will be updated to:

當你調用 twiceDaily(5, 14) 時表達式會更新成這樣:

0 5,14 * * * *

A very smart abstraction layer that saves you tons of research to find the right cron expression, however you can pass your own expression if you want as well:

一個很是聰明的抽象層,能夠節省大量的精力來找到正確的cron表達式,可是若是你只要你想你也能夠傳遞你本身的表達式:

$schedule->command('mail:send')->cron('0 * * * * *');

How about timezones?

如何設置時區?

If you want the CRON expression to be evaluated with respect to a specific timezone you can do that using:

若是您但願CRON表達式針對特定時區,則可使用如下方式進行:

->timezone('Europe/London')

Under the hood Laravel checks the timezone value you set and update the Carbon date instance to reflect that.

Laravel檢查您設置的時區值,並更新 Carbon 日期實例使其起做用。

So laravel checks if the command is due using the CRON expression?

那麼Laravel會用CRON表達式檢查命令是否到期嗎?

Exactly, Laravel uses the mtdowling/cron-expression library to determine if the command is due based on the current system time (with respect to the timezone we set).

偏偏相反,Laravel使用 mtdowling/cron-expression 庫來肯定命令是否基於當前系統時間(相對於咱們設置的時區)。

Adding Constraints on running the command

Duration constraints

在運行命令時添加限制

持續時間限制

For example if you want the command to run daily but only between two specific dates:

例如,若是您但願命令天天運行,但只能在兩個特定日期之間運行:

->between('2017-05-27', '2017-06-26')->daily();

And if you want to prevent it from running during a specific period:

若是你想防止它在一段特定的時間內運行:

->unlessBetween('2017-05-27', '2017-06-26')->daily();

Environment constraints

環境限制

You can use the environments() method to pass the list of environments the command is allowed to run under:

您可使用 environments() 設置傳遞命令容許運行的環境列表:

->environments('staging', 'production');

Maintenance Mode

維護模式

By default scheduled commands won't run when the application is in maintenance mode, however you can change that by using:

默認狀況下,當應用程序處於維護模式時,調度的命令不會運行,可是您能夠經過使用如下命令來更改:

->evenInMaintenanceMode()

OS User

系統用戶

You can set the Operating System user that'll run the command using:

你能夠設置那個操做系統用戶來執行這個命令:

->user('forge')

Under the hood Laravel will use sudo -u forge to set the user on the operating system.

Laravel將使用 sudo -u forge 設置在操做系統上運行的用戶。

Custom Constraints

自定義限制

You can define your own custom constraint using the when() and skip() methods:

您可使用 when()skip() 方法定義自定義約束:

// Runs the command only when the user count is greater than 1000
->when(function(){
    return User::count() > 1000;
});

// Runs the command unless the user count is greater than 1000
->skip(function(){
    return User::count() > 1000;
});

Before and After callbacks

以前和以後回調函數

Using the before() and then() methods you can register callbacks that'll run before or after the command finishes execution:

使用 before()then() 方法能夠註冊在命令完成執行以前或以後運行的回調函數:

->before(function(){
    Mail::to('myself@Mail.com', new CommandStarted());
})
->then(function(){
    Mail::to('myself@Mail.com', new CommandFinished());
});

You can also ping URLs or webhooks using the pingBefore() and thenPing() methods:

您還可使用 pingBefore() and thenPing() 方法ping URL或webhooks:

->ping('https://my-webhook.com/start')->thenPing('https://my-webhook.com/finish')

Using these commands laravel registers a before/after callbacks under the hood and uses Guzzle to send a GET HTTP request:

使用這些命令laravel在註冊一個前/後回調,並使用Guzzle發送一個 GET HTTP請求:

return $this->before(function () use ($url) {
    (new HttpClient)->get($url);
});

轉載請註明: 轉載自Ryan是菜鳥 | LNMP技術棧筆記

若是以爲本篇文章對您十分有益,何不 打賞一下

謝謝打賞

本文連接地址: 剖析Laravel計劃任務--事件屬性

相關文章
相關標籤/搜索