イントロダクション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 Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
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 use invokable
objects[https://secure.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 Taylor --force')->daily();
$schedule->command(EmailsCommand::class, ['Taylor', '--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
タスクにはさまざまなスケジュールを割り付けることができます。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 |
->everyTwoMinutes(); ->everyTwoMinutes(); |
2分毎にタスク実行Run the task every two minutes |
->everyThreeMinutes(); ->everyThreeMinutes(); |
3分毎にタスク実行Run the task every three minutes |
->everyFourMinutes(); ->everyFourMinutes(); |
4分毎にタスク実行Run the task every four minutes |
->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); |
1時間ごと、毎時17分にタスク実行Run the task every hour at 17 minutes past the hour |
->everyTwoHours(); ->everyTwoHours(); |
2時間毎にタスク実行Run the task every two hours |
->everyThreeHours(); ->everyThreeHours(); |
3時間毎にタスク実行Run the task every three hours |
->everyFourHours(); ->everyFourHours(); |
4時間毎にタスク実行Run the task every four hours |
->everySixHours(); ->everySixHours(); |
6時間毎にタスク実行Run the task every six hours |
->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(); |
毎週日曜日の00:00にタスク実行Run the task every sunday at 00:00 |
->weeklyOn(1, '8:00'); ->weeklyOn(1,
'8:00'); |
毎週月曜日の8:00時に実行Run the task every week on Monday at 8:00 |
->monthly(); ->monthly(); |
毎月1日の00:00にタスク実行Run the task on the first day of every month at 00:00 |
->monthlyOn(4,
'15:00'); ->monthlyOn(4,
'15:00'); |
毎月4日の15:00に実行Run the task every month on the 4th at 15:00 |
->lastDayOfMonth('15:00'); ->lastDayOfMonth('15:00'); |
毎月最終日の15:00時に実行Run the task on the last day of the month at 15:00 |
->quarterly(); ->quarterly(); |
四半期の初日の00:00にタスク実行Run the task on the first day of every quarter at 00:00 |
->yearly(); ->yearly(); |
毎年1月1日の00:00にタスク実行Run the task on the first day of every year at 00:00 |
->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:
// 週に1回、月曜の13:00に実行
$schedule->call(function () {
//
})->weekly()->mondays()->at('13:00');
// ウィークエンドの8時から17時まで1時間ごとに実行
$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 |
->weekends(); ->weekends(); |
ウィークエンドのみに限定Limit the task to weekends |
->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 |
`->days(array`->days(array | mixed);`mixed);` |
->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 |
->environments($env); ->environments($env); |
指定の環境でのみタスク実行を限定Limit the task to specific environments |
曜日の限定Day Constraints
days
メソッドはタスクを週の指定した曜日に実行するように制限するために使用します。たとえば、日曜日と水曜日に毎時コマンドを実行するようにスケジュールするには次のように指定します。The days
method may
be used to limit the execution of a task to specific
days of the week. For example, you may schedule a
command to run hourly on Sundays and
Wednesdays:
$schedule->command('reminders:send')
->hourly()
->days([0, 3]);
時間制限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
.
環境制約Environment Constraints
environments
メソッドは指定した環境時のみ、タスクを実行するために使用します。The environments
method may be used to execute tasks only on the
given environments:
$schedule->command('emails:send')
->daily()
->environments(['staging', 'production']);
タイムゾーン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')
スケジュール済みの全タスクへ同じタイムゾーンを指定する場合は、app/Console/Kernel.php
ファイル中でscheduleTimezone
メソッドを定義してください。このメソッドで全スケジュール済みタスクに適用する、デフォルトのタイムゾーンを返します。If you are assigning the same
timezone to all of your scheduled tasks, you may
wish to define a scheduleTimezone
method in your app/Console/Kernel.php
file. This method should return the default timezone
that should be assigned to all scheduled
tasks:
/**
* スケジュールされたイベントで使用するデフォルトのタイムゾーン取得
*
* @return \DateTimeZone|string|null
*/
protected function scheduleTimezone()
{
return 'America/Chicago';
}
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:
この機能を使用するには、アプリケーションのデフォルトキャッシュドライバとして、database
、memcached
、redis
キャッシュドライバを使用する必要があります。さらに、全サーバが同じ単一のキャッシュサーバと通信している必要があります。{note} To utilize this feature, your application must be using thedatabase
,memcached
, 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();
バックグランドタスクBackground Tasks
デフォルトでは、同じ時間にスケジュールされている複数のコマンドは、順次実行されます。実行時間のかかるコマンドがある場合、それ以降のコマンドが期待している時間より遅れて起動されてしまいます。すべてを同時に実行するには、runInBackground
メソッドを使用し、コマンドをバックグランドで実行してください。By default, multiple commands
scheduled at the same time will execute
sequentially. If you have long-running commands,
this may cause subsequent commands to start much
later than anticipated. If you would like to run
commands in the background so that they may all run
simultaneously, you may use the
runInBackground
method:
$schedule->command('analytics:report')
->daily()
->runInBackground();
Note:
runInBackground
メソッドはcommand
かexec
メソッドにより、タスクをスケジュールするときにのみ使用してください。{note} TherunInBackground
method may only be used when scheduling tasks via thecommand
andexec
methods.
メンテナンスモード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');
コマンド失敗時に出力をメール送信したい場合は、emailOutputOnFailure
メソッドを使用します。If you only want to e-mail the
output if the command fails, use the
emailOutputOnFailure
method:
$schedule->command('foo')
->daily()
->emailOutputOnFailure('foo@example.com');
Note:
emailOutputTo
、emailOutputOnFailure
、sendOutputTo
、appendOutputTo
メソッドは、command
とexec
メソッドに対してどれか一つしか指定できません。{note} TheemailOutputTo
,emailOutputOnFailure
,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 () {
// タスク終了時…
});
onSuccess
とonFailure
メソッドにより、そのスケジュールタスクが成功・失敗した時に特定のコードを実行できます。The onSuccess
and
onFailure
methods allow you to specify
code to be executed if the scheduled task succeeds
or fails:
$schedule->command('emails:send')
->daily()
->onSuccess(function () {
// タスク成功時…
})
->onFailure(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);
pingBeforeIf
とthenPingIf
メソッドは、指定した条件がtrue
のときのみ、指定URLへPingするために使用します。The pingBeforeIf
and
thenPingIf
methods may be used to ping
a given URL only if the given condition is
true
:
$schedule->command('emails:send')
->daily()
->pingBeforeIf($condition, $url)
->thenPingIf($condition, $url);
pingOnSuccess
とpingOnFailure
メソッドは、タスクが成功・失敗したときに指定URLへPingするために使用します。The pingOnSuccess
and pingOnFailure
methods may be used
to ping a given URL only if the task succeeds or
fails:
$schedule->command('emails:send')
->daily()
->pingOnSuccess($successUrl)
->pingOnFailure($failureUrl);
これらのPingメソッドすべてで、Guzzle HTTPライブラリが必要です。Composerパッケージマネージャを使用して、プロジェクトにGuzzleを追加できます。All of the ping methods require the Guzzle HTTP library. You can add Guzzle to your project using the Composer package manager:
composer require guzzlehttp/guzzle