イントロダクションIntroduction
コンソールコマンドを一つ一つスケジュールするため、今まで開発者はCronエントリーを毎回作成してきました。しかしこれは悩みの種でした。コンソールの実行スケジュールはソース管理されていませんでしたし、Cronのエントリを追加するためにその都度SSHでサーバーに接続する必要がありました。人生をより簡単に生きましょう。Laravelコマンドスケジューラーを使い、サーバーにCronエントリーを一つ追加するだけで、他に何も用意しなくてもLaravelだけでコマンド実行スケジュールをスラスラと記述的に定義することができます。In the past, developers have generated a Cron entry for each task they need to schedule. However, this is a headache. Your task schedule is no longer in source control, and you must SSH into your server to add the Cron entries. The Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
コマンドスケジュールはapp/Console/Kernel.php
ファイルに記述します。このクラスの中にschedule
メソッドが見つかるでしょう。始めやすいように、このメソッドの中に簡単な例を準備してあります。好きなだけジョブスケジュールをSchedule
オブジェクトに追加してください。Your task schedule is defined in
the app/Console/Kernel.php
file's
schedule
method. To help you get
started, a simple example is included with the
method. You are free to add as many scheduled tasks
as you wish to the Schedule
object.
スケジューラーを使いはじめるStarting The Scheduler
唯一以下のCronエントリーだけ、サーバーに追加してください。Here is the only Cron entry you need to add to your server:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
このCronエントリは、Laravelコマンドスケジューラーを毎分呼び出します。それにより、Laravelはスケジュールされているジョブを評価し、実行する必要のあるジョブを起動します。これ以上簡単にできません!This Cron will call the Laravel command scheduler every minute. Then, Laravel evaluates your scheduled tasks and runs the tasks that are due.
スケジュール定義Defining Schedules
スケジュールタスクは全部App\Console\Kernel
クラスのschedule
メソッドの中に定義します。手始めに、スケジュールタスクの例を見てください。この例は毎日深夜12時に「クロージャ」をスケジュールしています。「クロージャ」の中でテーブルをクリアするデータベースクエリを実行しています。You may define all of your
scheduled tasks in the schedule
method
of the App\Console\Kernel
class. To get
started, let's look at an example of scheduling a
task. In this example, we will schedule a
Closure
to be called every day at
midnight. Within the Closure
we will
execute a database query to clear a
table:
<?php
namespace App\Console;
use DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* アプリケーションで提供するArtisanコマンド
*
* @var array
*/
protected $commands = [
\App\Console\Commands\Inspire::class,
];
/**
* アプリケーションのコマンド実行スケジュール定義
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
}
}
「クロージャ」の呼び出しをスケジュールするほかにArtisanコマンドとオペレーティングシステムコマンドを実行できます。例としてArtisanコマンドをスケジュールするcommand
メソッドを使ってみましょう。In addition to scheduling
Closure
calls, you may also schedule
Artisan commands[/docs/{{version}}/artisan]
and operating system commands. For example, you may
use the command
method to schedule an
Artisan command:
$schedule->command('emails:send --force')->daily();
オペレーティングシステムでコマンドを実行するためにはexec
メソッドを使います。The exec
command may
be used to issue a command to the operating
system:
$schedule->exec('node /home/forge/script.js')->daily();
繰り返しのスケジュールオプションSchedule Frequency Options
もちろん、タスクは様々なスケジュールを割り付けることができます。Of course, there are a variety of schedules you may assign to your task:
メソッドMethod | 説明Description |
---|---|
->cron('* * * * * *'); ->cron('* * * * * *'); |
CRON記法によるスケジュールRun the task on a custom Cron schedule |
->everyMinute(); ->everyMinute(); |
毎分タスク実行Run the task every minute |
->everyFiveMinutes(); ->everyFiveMinutes(); |
5分毎にタスク実行Run the task every five minutes |
->everyTenMinutes(); ->everyTenMinutes(); |
10分毎にタスク実行Run the task every ten minutes |
->everyThirtyMinutes(); ->everyThirtyMinutes(); |
30分毎にタスク実行Run the task every thirty minutes |
->hourly(); ->hourly(); |
毎時タスク実行Run the task every hour |
->daily(); ->daily(); |
毎日深夜12時に実行Run the task every day at midnight |
->dailyAt('13:00'); ->dailyAt('13:00'); |
毎日13:00に実行Run the task every day at 13:00 |
->twiceDaily(1, 13); ->twiceDaily(1,
13); |
毎日1:00と13:00時に実行Run the task daily at 1:00 & 13:00 |
->weekly(); ->weekly(); |
毎週実行Run the task every week |
->monthly(); ->monthly(); |
毎月実行Run the task every month |
->monthlyOn(4,
'15:00'); ->monthlyOn(4,
'15:00'); |
毎月4日の15:00に実行Run the task every month on the 4th at 15:00 |
->quarterly(); ->quarterly(); |
四半期ごとに実行Run the task every quarter |
->yearly(); ->yearly(); |
毎年実行Run the task every year |
->timezone('America/New_York'); ->timezone('America/New_York'); |
タイムゾーン設定Set the timezone |
これらのメソッドは週の特定の曜日だけに実行させるために、追加の制約と組み合わせ細かく調整できます。These methods may be combined with additional constraints to create even more finely tuned schedules that only run on certain days of the week. For example, to schedule a command to run weekly on Monday:
// 週に一回、月曜の13:00に実行
$schedule->call(function () {
//
})->weekly()->mondays()->at('13:00');
// ウィークエンドの8時から17時まで一時間ごとに実行
$schedule->command('foo')
->weekdays()
->hourly()
->timezone('America/Chicago')
->when(function () {
return date('H') >= 8 && date('H') <= 17;
});
以下が追加のスケジュール制約のリストです。Below is a list of the additional schedule constraints:
メソッドMethod | 説明Description |
---|---|
->weekdays(); ->weekdays(); |
ウイークデーのみに限定Limit the task to weekdays |
->sundays(); ->sundays(); |
日曜だけに限定Limit the task to Sunday |
->mondays(); ->mondays(); |
月曜だけに限定Limit the task to Monday |
->tuesdays(); ->tuesdays(); |
火曜だけに限定Limit the task to Tuesday |
->wednesdays(); ->wednesdays(); |
水曜だけに限定Limit the task to Wednesday |
->thursdays(); ->thursdays(); |
木曜だけに限定Limit the task to Thursday |
->fridays(); ->fridays(); |
金曜だけに限定Limit the task to Friday |
->saturdays(); ->saturdays(); |
土曜だけに限定Limit the task to Saturday |
->when(Closure); ->when(Closure); |
クロージャの戻り値がture の時のみに限定Limit the task based
on a truth test |
真値テスト制約Truth Test Constraints
when
メソッドは指定した真値テストの結果に基づき制限を実行します。言い換えれば指定した「クロージャ」がture
を返し、他の制約が実行を停止しない限りタスクを実行します。The when
method may
be used to limit the execution of a task based on
the result of a given truth test. In other words, if
the given Closure
returns
true
, the task will execute as long as
no other constraining conditions prevent the task
from running:
$schedule->command('emails:send')->daily()->when(function () {
return true;
});
skip
メソッドはwhen
をひっくり返したものです。skip
メソッドへ渡したクロージャがtrue
を返した時、スケジュールタスクは実行されません。The skip
method may
be seen as the inverse of when
. If the
skip
method returns true
,
the scheduled task will not be executed:
$schedule->command('emails:send')->daily()->skip(function () {
return true;
});
when
メソッドをいくつかチェーンした場合は、全部のwhen
条件がtrue
を返すときのみスケジュールされたコマンドが実行されます。When using chained
when
methods, the scheduled command
will only execute if all when
conditions return true
.
タスク多重起動の防止Preventing Task Overlaps
デフォルトでは以前の同じジョブが起動中であっても、スケジュールされたジョブは実行されます。これを防ぐには、withoutOverlapping
メソッドを使用してください。By default, scheduled tasks will
be run even if the previous instance of the task is
still running. To prevent this, you may use the
withoutOverlapping
method:
$schedule->command('emails:send')->withoutOverlapping();
この例の場合、emails:send
Artisanコマンドは実行中でない限り毎分実行されます。withoutOverlapping
メソッドは指定したタスクの実行時間の変動が非常に大きく、予想がつかない場合に特に便利です。In this example, the
emails:send
Artisan
command[/docs/{{version}}/artisan] will be
run every minute if it is not already running. The
withoutOverlapping
method is especially
useful if you have tasks that vary drastically in
their execution time, preventing you from predicting
exactly how long a given task will take.
タスク出力Task Output
Laravelスケジューラーはスケジュールしたタスクが生成する出力を取り扱う便利なメソッドをたくさん用意しています。最初にsendOutputTo
メソッドを使い、後ほど内容を調べられるようにファイルへ出力してみましょう。The Laravel scheduler provides
several convenient methods for working with the
output generated by scheduled tasks. First, using
the sendOutputTo
method, you may send
the output to a file for later
inspection:
$schedule->command('emails:send')
->daily()
->sendOutputTo($filePath);
出力を指定したファイルに追加したい場合は、appendOutputTo
メソッドを使います。If you would like to append the
output to a given file, you may use the
appendOutputTo
method:
$schedule->command('emails:send')
->daily()
->appendOutputTo($filePath);
emailOutputTo
メソッドを使えば、選択したメールアドレスへ出力をメールで送ることができます。最初にsendOutputTo
メソッドを使い、ファイルへ出力しておく必要があることに注意してください。また、タスクの出力をメールで送る前に、Laravelのメールサービスの設定を済ませておく必要もあります。Using the
emailOutputTo
method, you may e-mail
the output to an e-mail address of your choice. Note
that the output must first be sent to a file using
the sendOutputTo
method. Also, before
e-mailing the output of a task, you should configure
Laravel's e-mail
services[/docs/{{version}}/mail]:
$schedule->command('foo')
->daily()
->sendOutputTo($filePath)
->emailOutputTo('foo@example.com');
注意:
emailOutputTo
とsendOutputTo
メソッドはcommand
メソッド専用で、call
メソッドはサポートしていません。Note: TheemailOutputTo
andsendOutputTo
methods are exclusive to thecommand
method and are not supported forcall
.
タスクフックTask Hooks
before
とafter
メソッドを使えば、スケジュールされたタスクの実行前後に指定したコードを実行することができます。Using the before
and
after
methods, you may specify code to
be executed before and after the scheduled task is
complete:
$schedule->command('emails:send')
->daily()
->before(function () {
// タスク開始時…
})
->after(function () {
// タスク終了時…
});
URLへのPingPinging URLs
pingBefore
とthenPing
メソッドを使用し、タスク実行前後に指定したURLへ自動的にPingすることができます。これはLaravel
Envoyerのような外部サービスへスケジュールされたタスクが始まる、または完了したことを知らせるのに便利です。Using the pingBefore
and thenPing
methods, the scheduler can
automatically ping a given URL before or after a
task is complete. This method is useful for
notifying an external service, such as Laravel
Envoyer[https://envoyer.io], that your
scheduled task is commencing or complete:
$schedule->command('emails:send')
->daily()
->pingBefore($url)
->thenPing($url);
pingBefore($url)
かthenPing($url)
のどちらを使用するにも、Guzzle
HTTPライブラリーが必要です。Guzzleはcomposer.json
ファイルに以下の行を追加してプロジェクトに追加できます。Using either the
pingBefore($url)
or
thenPing($url)
feature requires the
Guzzle HTTP library. You can add Guzzle to your
project by adding the following line to your
composer.json
file:
"guzzlehttp/guzzle": "~5.3|~6.0"