Readouble

Laravel 8.x タスクスケジュール

イントロダクションIntroduction

以前は、サーバでスケジュールする必要のあるタスクごとにcron設定エントリを作成する必要がありました。しかしながら、タスクスケジュールがソース管理されないため、これはすぐに苦痛になる可能性があります。既存のcronエントリを表示したり、エントリを追加したりするには、サーバへSSHで接続する必要がありました。In the past, you may have written a cron configuration 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 view your existing cron entries or add additional entries.

Laravelのコマンドスケジューラは、サーバ上でスケジュールするタスクを管理するための新しいアプローチを提供しています。スケジューラを使用すると、Laravelアプリケーション自体の中でコマンドスケジュールを流暢かつ表現力豊かに定義できます。スケジューラを使用する場合、サーバに必要なcronエントリは1つだけです。タスクスケジュールは、app/Console/Kernel.phpファイルのscheduleメソッドで定義されます。手を付けるのに役立つように、メソッド内に簡単な例が定義されています。Laravel's command scheduler offers a fresh approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Laravel application 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.

スケジュール定義Defining Schedules

スケジュールするすべてのタスクは、アプリケーションのApp\Console\Kernelクラスのscheduleメソッドで定義します。はじめに、例を見てみましょう。この例では、毎日深夜に呼び出されるようにクロージャをスケジュールします。クロージャ内で、データベースクエリを実行してテーブルをクリアします。You may define all of your scheduled tasks in the schedule method of your application's App\Console\Kernel class. To get started, let's take a look at an example. 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
{
    /**
     * アプリケーションのコマンド実行スケジュール定義
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            DB::table('recent_users')->delete();
        })->daily();
    }
}

クロージャを使用したスケジュールに加えて、呼び出し可能なオブジェクトをスケジュールすることもできます。呼び出し可能なオブジェクトは、__invokeメソッドを含む単純なPHPクラスです。In addition to scheduling using closures, you may also schedule 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();

スケジュールしたタスクの概要と、次に実行がスケジュールされている時間を表示したい場合は、schedule:list Artisanコマンドを使用します。If you would like to view an overview of your scheduled tasks and the next time they are scheduled to run, you may use the schedule:list Artisan command:

php artisan schedule:list

ArtisanコマンドのスケジュールScheduling Artisan Commands

クロージャのスケジュールに加えて、Artisanコマンドおよびシステムコマンドをスケジュールすることもできます。たとえば、commandメソッドを使用して、コマンドの名前またはクラスのいずれかを使用してArtisanコマンドをスケジュールできます。In addition to scheduling closures, you may also schedule Artisan commands[/docs/{{version}}/artisan] and system commands. For example, you may use the command method to schedule an Artisan command using either the command's name or class.

コマンドのクラス名を使用してArtisanコマンドをスケジュールする場合、コマンドが呼び出されたときにコマンドに提供する必要がある追加のコマンドライン引数の配列を渡せます。When scheduling Artisan commands using the command's class name, you may pass an array of additional command-line arguments that should be provided to the command when it is invoked:

use App\Console\Commands\SendEmailsCommand;

$schedule->command('emails:send Taylor --force')->daily();

$schedule->command(SendEmailsCommand::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 queued jobs without using the call method to define closures to queue the job:

use App\Jobs\Heartbeat;

$schedule->job(new Heartbeat)->everyFiveMinutes();

オプションの2番目と3番目の引数をjobメソッドに指定して、ジョブのキューに入れるために使用するキュー名とキュー接続を指定できます。Optional second and third arguments may be provided to the job method which specifies the queue name and queue connection that should be used to queue the job:

use App\Jobs\Heartbeat;

// "sqs"接続の"heartbeats"キューにジョブをディスパッチ
$schedule->job(new Heartbeat, 'heartbeats', 'sqs')->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

指定間隔で実行するようにタスクを設定する方法の例をいくつか見てきました。しかし、タスクに割り当てることができるタスクスケジュールの間隔は他にもたくさんあります。We've already seen a few examples of how you may configure a task to run at specified intervals. However, there are many more task schedule frequencies that you may assign to a 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
->twiceMonthly(1, 16, '13:00');->twiceMonthly(1, 16, '13:00'); 毎月1日と16日の13:00にタスク実行Run the task monthly on the 1st and 16th at 13: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
->yearlyOn(6, 1, '17:00');->yearlyOn(6, 1, '17:00'); 毎年6月1日の17:00にタスク実行Run the task every year on June 1st at 17:00
->timezone('America/New_York');->timezone('America/New_York'); タスクのタイムゾーンを設定Set the timezone for the task

これらの方法を追加の制約と組み合わせてると、特定の曜日にのみ実行する、さらに細かく調整したスケジュールを作成できます。たとえば、毎週月曜日に実行するようにコマンドをスケジュールできます。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, you may 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');

追加のスケジュール制約のリストを以下にリストします。A list of additional schedule constraints may be found below:

メソッド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($startTime, $endTime);->between($startTime, $endTime); 開始と終了時間間にタスク実行を制限Limit the task to run between start and end times
->unlessBetween($startTime, $endTime);->unlessBetween($startTime, $endTime); 開始と終了時間間にタスクを実行しないよう制限Limit the task to not 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('emails:send')
                ->hourly()
                ->days([0, 3]);

または、タスクを実行する日を定義するときに、Illuminate\Console\Scheduling\Scheduleクラスで使用可能な定数を使用することもできます。Alternatively, you may use the constants available on the Illuminate\Console\Scheduling\Schedule class when defining the days on which a task should run:

use Illuminate\Console\Scheduling\Schedule;

$schedule->command('emails:send')
                ->hourly()
                ->days([Schedule::SUNDAY, Schedule::WEDNESDAY]);

時間制限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('emails: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('emails: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メソッドは、指定する環境でのみタスクを実行するために使用できます(APP_ENV環境変数で定義されます。)The environments method may be used to execute tasks only on the given environments (as defined by the APP_ENV environment variable[/docs/{{version}}/configuration#environment-configuration]):

$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('2:00')

スケジュールされたすべてのタスクに同じタイムゾーンを繰り返し割り当てる場合は、App\Console\KernelクラスでscheduleTimezoneメソッドを定義することをお勧めします。このメソッドは、スケジュールされたすべてのタスクに割り当てる必要があるデフォルトのタイムゾーンを返す必要があります。If you are repeatedly assigning the same timezone to all of your scheduled tasks, you may wish to define a scheduleTimezone method in your App\Console\Kernel class. 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 この機能を利用するには、アプリケーションのデフォルトのキャッシュドライバとしてdatabasememcacheddynamodbredisキャッシュドライバを使用している必要があります。さらに、すべてのサーバが同じ中央キャッシュサーバと通信している必要があります。{note} To utilize this feature, your application must be using the database, memcached, dynamodb, 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's scheduler 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

デフォルトでは、同時にスケジュールされた複数のタスクは、scheduleメソッドで定義された順序に基づいて順番に実行されます。長時間実行されるタスクがある場合、これにより、後続のタスクが予想よりもはるかに遅く開始される可能性があります。タスクをすべて同時に実行できるようにバックグラウンドで実行する場合は、runInBackgroundメソッドを使用できます。By default, multiple tasks scheduled at the same time will execute sequentially based on the order they are defined in your schedule method. If you have long-running tasks, this may cause subsequent tasks to start much later than anticipated. If you would like to run tasks 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

アプリケーションがメンテナンスモードの場合、アプリケーションのスケジュールされたタスクは実行されません。これは、タスクがそのサーバで実行している未完了のメンテナンスに干渉することを望まないためです。ただし、メンテナンスモードでもタスクを強制的に実行したい場合は、タスクを定義するときにevenInMaintenanceModeメソッドを呼び出すことができます。Your application's scheduled tasks will not run when the application 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 call the evenInMaintenanceMode method when defining the task:

$schedule->command('emails:send')->evenInMaintenanceMode();

スケジューラの実行Running The Scheduler

スケジュールするタスクを定義する方法を学習したので、サーバで実際にタスクを実行する方法について説明しましょう。schedule:run Artisanコマンドは、スケジュールしたすべてのタスクを評価し、サーバの現在の時刻に基づいてタスクを実行する必要があるかどうかを判断します。Now that we have learned how to define scheduled tasks, let's discuss how to actually run them on our server. The schedule:run Artisan command will evaluate all of your scheduled tasks and determine if they need to run based on the server's current time.

したがって、Laravelのスケジューラを使用する場合、サーバに1分ごとにschedule:runコマンドを実行する単一のcron設定エントリを追加するだけで済みます。サーバにcronエントリを追加する方法がわからない場合は、Laravel Forgeなどのcronエントリを管理できるサービスの使用を検討してください。So, when using Laravel's scheduler, we only need to add a single cron configuration entry to our server that runs the schedule:run command every minute. 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

スケジュールをローカルで実行Running The Scheduler Locally

通常、ローカル開発マシンにスケジューラのcronエントリを追加することはありません。代わりに、schedule:work Artisanコマンドを使用できます。このコマンドはフォアグラウンドで実行し、コマンドを終了するまで1分ごとにスケジューラーを呼び出します。Typically, you would not add a scheduler cron entry to your local development machine. Instead, you may use the schedule:work Artisan command. This command will run in the foreground and invoke the scheduler every minute until you terminate the command:

php artisan schedule:work

タスク出力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メソッドを使用して、選択した電子メールアドレスへ出力を電子メールで送信できます。タスクの出力をメールで送信する前に、Laravelのメールサービスを設定する必要があります。Using the emailOutputTo method, you may email the output to an email address of your choice. Before emailing the output of a task, you should configure Laravel's email services[/docs/{{version}}/mail]:

$schedule->command('report:generate')
         ->daily()
         ->sendOutputTo($filePath)
         ->emailOutputTo('taylor@example.com');

スケジュールしたArtisanまたはシステムコマンドが、ゼロ以外の終了コードで終了した場合にのみ出力を電子メールで送信する場合は、emailOutputOnFailureメソッドを使用します。If you only want to email the output if the scheduled Artisan or system command terminates with a non-zero exit code, use the emailOutputOnFailure method:

$schedule->command('report:generate')
         ->daily()
         ->emailOutputOnFailure('taylor@example.com');

Note: note emailOutputToemailOutputOnFailuresendOutputToappendOutputToメソッドは、commandexecメソッドに対してのみ指定できます。{note} The emailOutputTo, emailOutputOnFailure, sendOutputTo, and appendOutputTo methods are exclusive to the command and exec 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 executed:

$schedule->command('emails:send')
         ->daily()
         ->before(function () {
             // タスクが実行されようとしている
         })
         ->after(function () {
             // タスクが実行された
         });

onSuccessメソッドとonFailureメソッドを使用すると、スケジュールされたタスクが成功または失敗した場合に実行されるコードを指定できます。失敗は、スケジュールされたArtisanまたはシステムコマンドがゼロ以外の終了コードで終了したことを示します。The onSuccess and onFailure methods allow you to specify code to be executed if the scheduled task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:

$schedule->command('emails:send')
         ->daily()
         ->onSuccess(function () {
             // タスク成功時…
         })
         ->onFailure(function () {
             // タスク失敗時…
         });

コマンドから出力を利用できる場合は、フックのクロージャの定義で$output引数としてIlluminate\Support\Stringableインスタンスを型指定することで、afteronSuccess、またはonFailureフックでアクセスできます。If output is available from your command, you may access it in your after, onSuccess or onFailure hooks by type-hinting an Illuminate\Support\Stringable instance as the $output argument of your hook's closure definition:

use Illuminate\Support\Stringable;

$schedule->command('emails:send')
         ->daily()
         ->onSuccess(function (Stringable $output) {
             // タスク成功時…
         })
         ->onFailure(function (Stringable $output) {
             // タスク失敗時…
         });

URLへのPingPinging URLs

pingBeforeメソッドとthenPingメソッドを使用すると、スケジューラーはタスクの実行前または実行後に、指定するURLに自動的にpingを実行できます。このメソッドは、Envoyerなどの外部サービスに、スケジュールされたタスクが実行を開始または終了したことを通知するのに役立ちます。Using the pingBefore and thenPing methods, the scheduler can automatically ping a given URL before or after a task is executed. This method is useful for notifying an external service, such as Envoyer[https://envoyer.io], that your scheduled task is beginning 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 a given condition is true:

$schedule->command('emails:send')
         ->daily()
         ->pingBeforeIf($condition, $url)
         ->thenPingIf($condition, $url);

pingOnSuccessメソッドとpingOnFailureメソッドは、タスクが成功または失敗した場合にのみ、特定のURLにpingを実行するために使用します。失敗は、スケジュールされたArtisanまたはシステムコマンドがゼロ以外の終了コードで終了したことを示します。The pingOnSuccess and pingOnFailure methods may be used to ping a given URL only if the task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:

$schedule->command('emails:send')
         ->daily()
         ->pingOnSuccess($successUrl)
         ->pingOnFailure($failureUrl);

すべてのpingメソッドにGuzzle HTTPライブラリが必要です。Guzzleは通常、デフォルトですべての新しいLaravelプロジェクトにインストールされますが、誤って削除した場合は、Composerパッケージマネージャーを使用してプロジェクトへ自分でGuzzleをインストールできます。All of the ping methods require the Guzzle HTTP library. Guzzle is typically installed in all new Laravel projects by default, but, you may manually install Guzzle into your project using the Composer package manager if it has been accidentally removed:

composer require guzzlehttp/guzzle

イベントEvents

必要に応じて、スケジューラーから送られてくるイベントをリッスンすることもできます。通常、イベントリスナのマッピングは、アプリケーションのApp\Providers\EventServiceProviderクラス内で定義します。If needed, you may listen to events[/docs/{{version}}/events] dispatched by the scheduler. Typically, event listener mappings will be defined within your application's App\Providers\EventServiceProvider class:

/**
 * アプリケーションのイベントリスナのマッピング
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Console\Events\ScheduledTaskStarting' => [
        'App\Listeners\LogScheduledTaskStarting',
    ],

    'Illuminate\Console\Events\ScheduledTaskFinished' => [
        'App\Listeners\LogScheduledTaskFinished',
    ],

    'Illuminate\Console\Events\ScheduledBackgroundTaskFinished' => [
        'App\Listeners\LogScheduledBackgroundTaskFinished',
    ],

    'Illuminate\Console\Events\ScheduledTaskSkipped' => [
        'App\Listeners\LogScheduledTaskSkipped',
    ],

    'Illuminate\Console\Events\ScheduledTaskFailed' => [
        'App\Listeners\LogScheduledTaskFailed',
    ],
];

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作