Readouble

Laravel 5.8 タスクスケジュール

イントロダクション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\Support\Facades\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 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
->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
->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
->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

時間制限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 タイムゾーンの中には夏時間を取り入れているものがあることを忘れないでください。夏時間の切り替えにより、スケジュールされたタスクが2回実行されたり、全くされないことがあります。そのため、可能であればタイムゾーンによるスケジュールは使用しないことをおすすめします。{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.

タスク多重起動の防止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: note この機能を使用するには、アプリケーションのデフォルトキャッシュドライバとして、memcachedredisキャッシュドライバを使用する必要があります。更に、全サーバが同じ単一のキャッシュサーバと通信している必要があります。{note} To utilize this feature, your application must be using the memcached or redis 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: note runInBackgroundメソッドはcommandexecメソッドにより、タスクをスケジュールするときにのみ使用してください。{note} The runInBackground method may only be used when scheduling tasks via the command and exec 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: note emailOutputToemailOutputOnFailuresendOutputToappendOutputToメソッドは、commandexecメソッドに対してどれか一つしか指定できません。{note} The emailOutputTo, emailOutputOnFailure, sendOutputTo, and appendOutputTo methods are exclusive to the command and exec methods.

タスクフックTask Hooks

beforeafterメソッドを使えば、スケジュールされたタスクの実行前後に指定したコードを実行することができます。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 () {
             // タスク終了時…
         });

onSuccessonFailureメソッドにより、そのスケジュールタスクが成功・失敗した時に特定のコードを実行できます。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

pingBeforethenPingメソッドを使用し、タスク実行前、タスク完了後に指定した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);

pingBeforeIfthenPingIfメソッドは、指定した条件が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);

pingOnSuccesspingOnFailureメソッドは、タスクが成功・失敗したときに指定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

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作