イントロダクションIntroduction
今までは実行をスケジュールする必要のあるタスクごとにサーバで、Cronエントリを制作していたかと思います。しかし、これはすぐに面倒になります。In the past, you may have generated a Cron entry for each task you needed to schedule on your server. However, this can quickly become a pain, because your task schedule is no longer in source control and you must SSH into your server to add additional Cron entries.
Laravelのコマンドスケジューラは、Laravel自身の中でコマンドの実行スケジュールをスラスラと記述的に定義できるようにしてくれます。スケジューラを使用すると、サーバにはCronエントリがたった一つだけで済みます。タスクスケジュールは、app/Console/Kernel.php
ファイルのschedule
メソッドで定義します。使いはじめる手助けになるように、サンプルがこのメソッド中で定義してあります。Laravel's command scheduler
allows you to fluently and expressively define your
command schedule within Laravel itself. When using
the scheduler, only a single Cron entry is needed on
your server. Your task schedule is defined in the
app/Console/Kernel.php
file's
schedule
method. To help you get
started, a simple example is defined within the
method.
スケジューラを使いはじめるStarting The Scheduler
スケジューラを使用するには、サーバに以下のCronエントリを追加するだけです。サーバにどうやってCronエントリを追加するかわからない場合は、Cronエントリを管理できるLaravel Forgeのようなサービスを使用することを考慮してください。When using the scheduler, you only need to add the following Cron entry to your server. If you do not know how to add Cron entries to your server, consider using a service such as Laravel Forge[https://forge.laravel.com] which can manage the Cron entries for you:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
このCronはLaravelコマンドスケジューラを毎分呼び出します。schedule:run
コマンドが実行されると、Laravelはスケジュールされているジョブを評価し、実行する必要のあるジョブを起動します。This Cron will call the Laravel
command scheduler every minute. When the
schedule:run
command is executed,
Laravel will evaluate 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 = [
//
];
/**
* アプリケーションのコマンド実行スケジュール定義
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
}
}
さらにクロージャを使用したスケジュールでは、invoke可能なオブジェクトも使用できます。Invoke可能なオブジェクトとは、単に__invoke
メソッドを含むPHPクラスのことです。In addition to scheduling using
Closures, you may also using invokable
objects[http://php.net/manual/en/language.oop5.magic.php#object.invoke].
Invokable objects are simple PHP classes that
contain an __invoke
method:
$schedule->call(new DeleteRecentUsers)->daily();
ArtisanコマンドのスケジュールScheduling Artisan Commands
「クロージャ」の呼び出しをスケジュールするほかに、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 using either the command's name or
class:
$schedule->command('emails:send --force')->daily();
$schedule->command(EmailsCommand::class, ['--force'])->daily();
キュー投入するジョブのスケジュールScheduling Queued Jobs
キュー投入するジョブをスケジュールするには、job
メソッドを使います。このメソッドを使うと、ジョブをキューに入れるためのクロージャを自前で作成するcall
メソッドを使わずとも、ジョブをスケジュール実行することができます。The job
method may
be used to schedule a queued
job[/docs/{{version}}/queues]. This method
provides a convenient way to schedule jobs without
using the call
method to manually
create Closures to queue the job:
$schedule->job(new Heartbeat)->everyFiveMinutes();
// ジョブを"heartbeats"キューへ投入する
$schedule->job(new Heartbeat, 'heartbeats')->everyFiveMinutes();
シェルコマンドのスケジュールScheduling Shell Commands
オペレーティングシステムでコマンドを実行するためにはexec
メソッドを使います。The exec
method 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 |
->everyFifteenMinutes(); ->everyFifteenMinutes(); |
15分毎にタスク実行Run the task every fifteen minutes |
->everyThirtyMinutes(); ->everyThirtyMinutes(); |
30分毎にタスク実行Run the task every thirty minutes |
->hourly(); ->hourly(); |
毎時タスク実行Run the task every hour |
->hourlyAt(17); ->hourlyAt(17); |
一時間ごと、毎時17分にタスク実行Run the task every hour at 17 mins past the 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 |
->weeklyOn(1, '8:00'); ->weeklyOn(1,
'8:00'); |
毎週月曜日の8:00時に実行Run the task every week on Monday at 8:00 |
->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')
->between('8:00', '17:00');
以下が追加のスケジュール制約のリストです。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 |
->between($start,
$end); ->between($start,
$end); |
開始と終了時間間にタスク実行を制限Limit the task to run between start and end times |
->when(Closure); ->when(Closure); |
クロージャの戻り値がtrue の時のみに限定Limit the task based
on a truth test |
時間制限Between Time Constraints
between
メソッドは一日の時間に基づき、実行時間を制限するために使用します。The between
method
may be used to limit the execution of a task based
on the time of day:
$schedule->command('reminders:send')
->hourly()
->between('7:00', '22:00');
同じように、unlessBetween
メソッドは、その時間にタスクの実行を除外するために使用します。Similarly, the
unlessBetween
method can be used to
exclude the execution of a task for a period of
time:
$schedule->command('reminders:send')
->hourly()
->unlessBetween('23:00', '4:00');
真値テスト制約Truth Test Constraints
when
メソッドは指定した真値テストの結果に基づき制限を実行します。言い換えれば指定した「クロージャ」がtrue
を返し、他の制約が実行を停止しない限りタスクを実行します。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
.
タイムゾーンTimezones
timezone
メソッドを使い、タスクのスケジュールをどこのタイムゾーンとみなすか指定できます。Using the timezone
method, you may specify that a scheduled task's time
should be interpreted within a given
timezone:
$schedule->command('report:generate')
->timezone('America/New_York')
->at('02:00')
Note: {note} Remember that some timezones utilize daylight savings time. When daylight saving time changes occur, your scheduled task may run twice or even not run at all. For this reason, we recommend avoiding timezone scheduling when possible.
タイムゾーンの中には夏時間を取り入れているものがあることを忘れないでください。夏時間の切り替えにより、スケジュールされたタスクが2回実行されたり、全くされないことがあります。そのため、可能であればタイムゾーンによるスケジュールは使用しないことをおすすめします。
タスク多重起動の防止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.
必要であれば、「重起動の防止(without overlapping)」ロックを期限切れにするまでに、何分間経過させるかを指定できます。時間切れまでデフォルトは、24時間です。If needed, you may specify how many minutes must pass before the "without overlapping" lock expires. By default, the lock will expire after 24 hours:
$schedule->command('emails:send')->withoutOverlapping(10);
単一サーバ上でのタスク実行Running Tasks On One Server
Note:
この機能を使用するには、アプリケーションのデフォルトキャッシュドライバとして、memcached
かredis
キャッシュドライバを使用する必要があります。更に、全サーバが同じ単一のキャッシュサーバと通信している必要があります。{note} To utilize this feature, your application must be using thememcached
orredis
cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.
アプリケーションが複数のサーバで実行される場合、スケジュール済みのジョブを単一サーバ上のみで実行するよう制限できるようになりました。たとえば、毎週の金曜の夜に、新しいレポートを生成するタスクをスケジュールしていると仮定しましょう。タスクスケジューラが3つのワーカーサーバ上で実行されているなら、スケジュールされているタスクは3つ全部のサーバで実行され、3回レポートが生成されます。これではいけません。If your application is running on multiple servers, you may limit a scheduled job to only execute on a single server. For instance, assume you have a scheduled task that generates a new report every Friday night. If the task scheduler is running on three worker servers, the scheduled task will run on all three servers and generate the report three times. Not good!
タスクをサーバひとつだけで実行するように指示するには、スケジュールタスクを定義するときにonOneServer
メソッドを使用します。このタスクを最初に取得したサーバが、同じタスクを同じCronサイクルで他のサーバで実行しないように、ジョブにアトミックなロックを確保します。To indicate that the task should
run on only one server, use the
onOneServer
method when defining the
scheduled task. The first server to obtain the task
will secure an atomic lock on the job to prevent
other servers from running the same task at the same
time:
$schedule->command('report:generate')
->fridays()
->at('17:00')
->onOneServer();
メンテナンスモードMaintenance Mode
Laravelのスケジュールタスクは、Laravelがメンテナンスモードの間は実行されません。メンテナンスが完了していないサーバ上で、タスクが実行されてほしくないからです。しかし、メンテナンスモードでも実行するように強制したい場合は、evenInMaintenanceMode
メソッドを使用します。Laravel's scheduled tasks will
not run when Laravel is in maintenance
mode[/docs/{{version}}/configuration#maintenance-mode],
since we don't want your tasks to interfere with any
unfinished maintenance you may be performing on your
server. However, if you would like to force a task
to run even in maintenance mode, you may use the
evenInMaintenanceMode
method:
$schedule->command('emails:send')->evenInMaintenanceMode();
タスク出力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
メソッドを使えば、選択したメールアドレスへ出力をメールで送ることができます。タスク出力をメールで送信する前に、メール送信サービスの設定を済ませておく必要があります。Using the
emailOutputTo
method, you may e-mail
the output to an e-mail address of your choice.
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');
Note:
emailOutputTo
、sendOutputTo
、appendOutputTo
メソッドは、command
とexec
メソッドに対して排他的です。{note} TheemailOutputTo
,sendOutputTo
andappendOutputTo
methods are exclusive to thecommand
andexec
methods.
タスクフック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 has finished
execution:
$schedule->command('emails:send')
->daily()
->pingBefore($url)
->thenPing($url);
pingBefore($url)
かthenPing($url)
のどちらを使用するにも、Guzzle
HTTPライブラリーが必要です。GuzzleはComposerパッケージマネージャを利用し追加できます。Using either the
pingBefore($url)
or
thenPing($url)
feature requires the
Guzzle HTTP library. You can add Guzzle to your
project using the Composer package
manager:
composer require guzzlehttp/guzzle