Readouble

Laravel 5.2 キュー

イントロダクションIntroduction

Laravelのキューサービスは、様々なキューバックエンドに対し共通のAPIを提供しています。キューによりメール送信のような時間を費やす処理を遅らせることが可能です。これによりアプリケーションのリクエストを徹底的に引き上げることができます。The Laravel queue service provides a unified API across a variety of different queue back-ends. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time which drastically speeds up web requests to your application.

設定Configuration

キューの設定ファイルはconfig/queue.phpです。このファイルにはフレームワークに含まれているそれぞれのドライバーへの接続設定が含まれています。それにはデータベース、BeanstalkdAmazon SQSRedis、同期(ローカル用途)ドライバーが含まれています。The queue configuration file is stored in config/queue.php. In this file you will find connection configurations for each of the queue drivers that are included with the framework, which includes a database, Beanstalkd[http://kr.github.com/beanstalkd], Amazon SQS[http://aws.amazon.com/sqs], Redis[http://redis.io], and synchronous (for local use) driver.

nullキュードライバはキューされたジョブが実行されないように、破棄するだけです。A null queue driver is also included which simply discards queued jobs.

ドライバ毎の必要要件Driver Prerequisites

データベースDatabase

databaseキュードライバを使用するには、ジョブを記録するためのデータベーステーブルが必要です。このテーブルを作成するマイグレーションはqueue:table Artisanコマンドにより生成できます。マイグレーションが生成されたら、migrateコマンドでデータベースをマイグレートしてください。In order to use the database queue driver, you will need a database table to hold the jobs. To generate a migration that creates this table, run the queue:table Artisan command. Once the migration is created, you may migrate your database using the migrate command:

php artisan queue:table

php artisan migrate

他のドライバに必要なパッケージOther Queue Dependencies

以下の依存パッケージがリストしたキュードライバを使用するために必要です。The following dependencies are needed for the listed queue drivers:

  • Amazon SQS: aws/aws-sdk-php ~3.0Amazon SQS: aws/aws-sdk-php ~3.0
  • Beanstalkd: pda/pheanstalk ~3.0Beanstalkd: pda/pheanstalk ~3.0
  • Redis: predis/predis ~1.0Redis: predis/predis ~1.0

ジョブクラスを書くWriting Job Classes

ジョブクラスの生成Generating Job Classes

キュー投入可能なアプリケーションの全ジョブは、デフォルトでapp/Jobsディレクトリへ保存されます。新しいキュー投入ジョブはArtisan CLIで生成できます。By default, all of the queueable jobs for your application are stored in the app/Jobs directory. You may generate a new queued job using the Artisan CLI:

php artisan make:job SendReminderEmail

このコマンドにより新しいクラスがapp/Jobsディレクトリに生成され、そのクラスは同期的に実行する代わりにキューへジョブを投入することをLaravelに知らせる目印となる、Illuminate\Contracts\Queue\ShouldQueueインターフェイスを実装しています。This command will generate a new class in the app/Jobs directory, and the class will implement the Illuminate\Contracts\Queue\ShouldQueue interface, indicating to Laravel that the job should be pushed onto the queue instead of run synchronously.

ジョブクラスの構造Job Class Structure

ジョブクラスはとてもシンプルでキューでジョブが処理されるときに呼び出されるhandleメソッドだけで通常構成されています。手始めにこのジョブクラスを確認してみましょう。Job classes are very simple, normally containing only a handle method which is called when the job is processed by the queue. To get started, let's take a look at an example job class:

<?php

namespace App\Jobs;

use App\User;
use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendReminderEmail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $user;

    /**
     * 新しいジョブインスタンスの生成
     *
     * @param  User  $user
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * ジョブの実行
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function handle(Mailer $mailer)
    {
        $mailer->send('emails.reminder', ['user' => $this->user], function ($m) {
            //
        });

        $this->user->reminders()->create(...);
    }
}

この例中、キュージョブのコンテナーに直接Eloquentモデルが渡せることに注目してください。ジョブが使用しているSerializesModelsトレイトによりEloquentモデルは優雅にシリアライズされ、ジョブが処理される時にアンシリアライズされます。キュー投入されたジョブがコンテナでEloquentモデルを受け取ると、モデルの識別子のみシリアライズされています。ジョブが実際に処理される時、キューシステムは自動的にデータベースから完全なモデルインスタンスを再取得します。これらは全てアプリケーションの完全な透過性のためであり、Eloquentモデルインスタンスをシリアライズするときに発生する問題を防ぐことができます。In this example, note that we were able to pass an Eloquent model[/docs/{{version}}/eloquent] directly into the queued job's constructor. Because of the SerializesModels trait that the job is using, Eloquent models will be gracefully serialized and unserialized when the job is processing. If your queued job accepts an Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database. It's all totally transparent to your application and prevents issues that can arise from serializing full Eloquent model instances.

handleメソッドはキューによりジョブが処理されるときに呼びだされます。ジョブのhandleメソッドにタイプヒントにより依存を指定できることに注目してください。Laravelのサービスコンテナが自動的に依存を注入します。The handle method is called when the job is processed by the queue. Note that we are able to type-hint dependencies on the handle method of the job. The Laravel service container[/docs/{{version}}/container] automatically injects these dependencies.

上手く行かない場合When Things Go Wrong

ジョブの実行時に例外が投げられると、再実行を試みるため自動的にキューへ戻されます。ジョブはアプリケーションが許している最大回数まで続けて再実行されます。最大再実行回数はqueue:listenqueue:work Artisanコマンド実行時に--triesスイッチで指定します。キューリスナの詳細はこの後に記述します。If an exception is thrown while the job is being processed, it will automatically be released back onto the queue so it may be attempted again. The job will continue to be released until it has been attempted the maximum number of times allowed by your application. The number of maximum attempts is defined by the --tries switch used on the queue:listen or queue:work Artisan jobs. More information on running the queue listener can be found below[#running-the-queue-listener].

ジョブを手動でリリースするManually Releasing Jobs

ジョブを自分で再実行したい場合、生成したジョブクラスでは含まれているInteractsWithQueueトレイトが提供するキュージョブのreleaseメソッドを使用してください。releaseメソッドは引数をひとつだけ取り、そのジョブを再実行可能にするまで待機する秒数を指定します。If you would like to release the job manually, the InteractsWithQueue trait, which is already included in your generated job class, provides access to the queue job release method. The release method accepts one argument: the number of seconds you wish to wait until the job is made available again:

public function handle(Mailer $mailer)
{
    if (condition) {
        $this->release(10);
    }
}

実行試行回数のチェックChecking The Number Of Run Attempts

前述の通り、ジョブの処理中に例外が起きた場合、そのジョブは自動的にキューに再登録されます。ジョブを実行しようとした試行回数をattemptsメソッドで調べることができます。As noted above, if an exception occurs while the job is being processed, it will automatically be released back onto the queue. You may check the number of attempts that have been made to run the job using the attempts method:

public function handle(Mailer $mailer)
{
    if ($this->attempts() > 3) {
        //
    }
}

ジョブのキュー投入Pushing Jobs Onto The Queue

デフォルトLaravelコントローラーのapp/Http/Controllers/Controller.phpDispatchesJobsトレイトを使っています。このトレイトはdispatchメソッドのような、キューへジョブを便利に投入できるようにいくつかのメソッドを提供しています。The default Laravel controller located in app/Http/Controllers/Controller.php uses a DispatchesJobs trait. This trait provides several methods allowing you to conveniently push jobs onto the queue, such as the dispatch method:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定ユーザーにリマインダーメールを送信する
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $this->dispatch(new SendReminderEmail($user));
    }
}

DispatchesJobsトレイトThe DispatchesJobs Trait

もちろんルートやコントローラーではないアプリケーションのどこからか、ジョブをディスパッチしたいこともあるでしょう。そのためDispatchesJobsトレイトはアプリケーションのどのクラスでも使えるようになっており、多くのディスパッチメソッドにアクセスできます。このトレイトを使用するサンプルクラスを見てください。Of course, sometimes you may wish to dispatch a job from somewhere in your application besides a route or controller. For that reason, you can include the DispatchesJobs trait on any of the classes in your application to gain access to its various dispatch methods. For example, here is a sample class that uses the trait:

<?php

namespace App;

use Illuminate\Foundation\Bus\DispatchesJobs;

class ExampleClass
{
    use DispatchesJobs;
}

dispatch関数The dispatch Function

もしくは、dispatchグローバル関数を使うこともできます。Or, you may use the dispatch global function:

Route::get('/job', function () {
    dispatch(new App\Jobs\PerformTask);

    return 'Done!';
});

ジョブのキュー指定Specifying The Queue For A Job

さらに特定のキューにジョブを送ることもできます。You may also specify the queue a job should be sent to.

ジョブを異なったキューに送ることでキューするジョブを「カテゴリー分け」できます。さらに様々なキューにいくつのワーカーを割りつけるかによりプライオリティー付けできます。これはキュー設定ファイルで定義されている別々のキュー「接続」へジョブを送るという意味ではなく、一つの接続に対しキューを指定するだけで実現できます。キューを指定するにはジョブインスタンスのonQueueメソッドを使います。onQueueメソッドはApp\Jobs\Job基礎クラスに含まれる、Illuminate\Bus\Queueableトレイトにより提供しています。By pushing jobs to different queues, you may "categorize" your queued jobs, and even prioritize how many workers you assign to various queues. This does not push jobs to different queue "connections" as defined by your queue configuration file, but only to specific queues within a single connection. To specify the queue, use the onQueue method on the job instance. The onQueue method is provided by the Illuminate\Bus\Queueable trait, which is already included on the App\Jobs\Job base class:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定ユーザにリマインダーメールを送信する
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $job = (new SendReminderEmail($user))->onQueue('emails');

        $this->dispatch($job);
    }
}

注意: DispatchesJobsトレイトは、デフォルトキュー接続のキューへジョブを投入します。Note: The DispatchesJobs trait pushes jobs to queues within the default queue connection.

ジョブのキュー接続指定Specifying The Queue Connection For A Job

複数のキュー接続を取り扱う場合、ジョブへ投入する接続を指定する必要が起きます。接続の指定には、ジョブインスタンスのonConnectionメソッドを使います。onConnectionメソッドはIlluminate\Bus\Queueableトレイトにより提供されており、App\Jobs\Jobベースクラスで取り込まれています。If you are working with multiple queue connections, you may specify which connection to push a job to. To specify the connection, use the onConnection method on the job instance. The onConnection method is provided by the Illuminate\Bus\Queueable trait, which is already included on the App\Jobs\Job base class:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定したユーザへリマインダーメールを送信
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $job = (new SendReminderEmail($user))->onConnection('alternate');

        $this->dispatch($job);
    }
}

もちろん、ジョブのキューと接続を指定するために、onConnectiononQueueメソッドをチェーンすることもできます。Of course, you can also chain the onConnection and onQueue methods to specify the connection and the queue for a job:

public function sendReminderEmail(Request $request, $id)
{
    $user = User::findOrFail($id);

    $job = (new SendReminderEmail($user))
                    ->onConnection('alternate')
                    ->onQueue('emails');

    $this->dispatch($job);

}

遅延ジョブDelayed Jobs

投入したキュージョブの実行を遅らせたい場合もあるでしょう。たとえばサインアップの5分後に顧客へメールを送信するジョブをキューしたい場合などです。この場合、Illuminate\Bus\Queueableトレイトが提供しているdelayメソッドを使用して下さい。Sometimes you may wish to delay the execution of a queued job. For instance, you may wish to queue a job that sends a customer a reminder e-mail 5 minutes after sign-up. You may accomplish this using the delay method on your job class, which is provided by the Illuminate\Bus\Queueable trait:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定したユーザへリマインダーメールを送信
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $job = (new SendReminderEmail($user))->delay(60 * 5);

        $this->dispatch($job);
    }
}

この例では、ワーカーで実行可能になるまで、キューの中のジョブを5分間遅延させると指定しています。In this example, we're specifying that the job should be delayed in the queue for 5 minutes before being made available to workers.

注目: Amazon SQSサービスには、遅延900秒(15分)という制限があります。Note: The Amazon SQS service has a maximum delay time of 15 minutes.

ジョブイベントJob Events

ジョブのライフサイクルイベントJob Lifecycle Events

Queue::beforeQueue::afterメソッドにより、キュージョブが実行開始した時と、成功裏に完了した時点で実行されるコールバックを登録することができます。コールバックにより、追加のログを残したり、続いて実行すべきジョブをキューへ投入したり、ダッシュボード上の回数を増加させたりする、タイミングが提供されます。例として、Laravelに含まれているAppServiceProviderで、このイベントにコールバックを指定してみます。The Queue::before and Queue::after methods allow you to register a callback to be executed before a queued job is started or when it executes successfully. The callbacks are great opportunity to perform additional logging, queue a subsequent job, or increment statistics for a dashboard. For example, we may attach a callback to this event from the AppServiceProvider that is included with Laravel:

<?php

namespace App\Providers;

use Queue;
use Illuminate\Support\ServiceProvider;
use Illuminate\Queue\Events\JobProcessed;

class AppServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションサービスの初期起動処理
     *
     * @return void
     */
    public function boot()
    {
        Queue::after(function (JobProcessed $event) {
            // $event->connectionName
            // $event->job
            // $event->data
        });
    }

    /**
     * サービスプロバイダの登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

キューリスナの実行Running The Queue Listener

キューリスナの起動Starting The Queue Listener

LaravelのArtisanは新しくキューに保存されたジョブを実行するコマンドを含んでいます。queue:listenコマンドを使いリスナを実行できます。Laravel includes an Artisan command that will run new jobs as they are pushed onto the queue. You may run the listener using the queue:listen command:

php artisan queue:listen

リスナに使用するキュー接続を指定することもできます。You may also specify which queue connection the listener should utilize:

php artisan queue:listen connection-name

このタスクを一度開始したら、手動で停止しない限り実行を続けることに注意してください。Supervisorのようなプロセスモニターを利用し、キューリスナが確実に動作し続けるようにしてください。Note that once this task has started, it will continue to run until it is manually stopped. You may use a process monitor such as Supervisor[http://supervisord.org/] to ensure that the queue listener does not stop running.

キューの優先度Queue Priorities

listenコマンドにキューのプライオリティーを設定するため、キュー接続をカンマ区切りで指定することもできます。You may pass a comma-delimited list of queue connections to the listen job to set queue priorities:

php artisan queue:listen --queue=high,low

この例でhighlowのジョブを実行する前にいつも処理されます。In this example, jobs on the high queue will always be processed before moving onto jobs from the low queue.

ジョブのタイムアウトパラメータ指定Specifying The Job Timeout Parameter

それぞれのジョブの実行時間を秒数で指定することもできます。You may also set the length of time (in seconds) each job should be allowed to run:

php artisan queue:listen --timeout=60

キュー休止時間の指定Specifying Queue Sleep Duration

さらに新しいジョブをポーリングする前に、待ち秒数を指定することもできます。In addition, you may specify the number of seconds to wait before polling for new jobs:

php artisan queue:listen --sleep=5

キューにジョブがない場合のみキューがスリープすることに注意して下さい。もしジョブが存在しているなら、キューはスリープせずに処理を続けます。Note that the queue only "sleeps" if no jobs are on the queue. If more jobs are available, the queue will continue to work them without sleeping.

キュー上の最初のジョブの実行Processing The First Job On The Queue

キューの最初のジョブだけを実行するには、queue:workコマンドを使います。To process only the first job on the queue, you may use the queue:work command:

php artisan queue:work

Supervisor設定Supervisor Configuration

SupervisorはLinuxオペレーティングシステムの監視プロセスで、queue:listenqueue:workコマンドが落ちていれば自動的に再起動してくれます。UbuntuにSupervisorをインストールするには、次のコマンドで行います。Supervisor is a process monitor for the Linux operating system, and will automatically restart your queue:listen or queue:work commands if they fail. To install Supervisor on Ubuntu, you may use the following command:

sudo apt-get install supervisor

Supervisorの設定ファイルは通常/etc/supervisor/conf.dディレクトリに保存します。このディレクトリの中には、Supervisorにどのようにプロセスを監視するのか指示する設定ファイルを好きなだけおくことができます。たとえば、laravel-worker.confファイルを作成し、queue:workプロセスを起動、監視させてみましょう。Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a laravel-worker.conf file that starts and monitors a queue:work process:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=forge
numprocs=8
redirect_stderr=true
stdout_logfile=/home/forge/app.com/worker.log

この例のnumprocsディレクティブはSupervisorに全部で8つのqueue:workプロセスを実行・監視し、落ちていれば自動的に再起動するように指示しています。もちろんcommandディレクティブのqueue:work sqsの部分を変更し、選択したドライバに合わせてください。In this example, the numprocs directive will instruct Supervisor to run 8 queue:work processes and monitor all of them, automatically restarting them if they fail. Of course, you should change the queue:work sqs portion of the command directive to reflect your chosen queue driver.

設定ファイルができたら、Supervisorの設定を更新し起動するために以下のコマンドを実行してください。Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands:

sudo supervisorctl reread

sudo supervisorctl update

sudo supervisorctl start laravel-worker:*

Supervisorの設定と使用法の詳細は、Supervisorのドキュメントを読んでください。もしくは便利なWebインターフェイスからSupervisorを設定、管理できるLaravel Forgeを使うこともできます。For more information on configuring and using Supervisor, consult the Supervisor documentation[http://supervisord.org/index.html]. Alternatively, you may use Laravel Forge[https://forge.laravel.com] to automatically configure and manage your Supervisor configuration from a convenient web interface.

デーモンキューリスナDaemon Queue Listener

queue:workはフレームワークを再起動せずに連続してジョブを処理し続けるようにキューワーカーを強制するために--daemonオプションも備えています。これによりqueue:listenと比較すると、CPU使用率を大幅に引き下げることができます。The queue:work Artisan command includes a --daemon option for forcing the queue worker to continue processing jobs without ever re-booting the framework. This results in a significant reduction of CPU usage when compared to the queue:listen command:

キュー・ワーカーをデーモンモードで開始するためには、--daemonフラッグを使用します。To start a queue worker in daemon mode, use the --daemon flag:

php artisan queue:work connection-name --daemon

php artisan queue:work connection-name --daemon --sleep=3

php artisan queue:work connection-name --daemon --sleep=3 --tries=3

ご覧の通りqueue:workコマンドはqueue:listenで使用できるものと、ほぼ同じオプションをサポートしています。php artisan help queue:workコマンドで全オプションを表示できます。As you can see, the queue:work job supports most of the same options available to queue:listen. You may use the php artisan help queue:work job to view all of the available options.

デーモンキューワーカー使用時のコーディング留意点Coding Considerations For Daemon Queue Listeners

デーモンキューワーカーは各ジョブを処理する前にフレームワークを再起動しません。そのため多くのリソースを使用するジョブを完了する前に、それらを開放するように気をつけてください。たとえばGDライブラリーを使用し画像処理を行う場合、完了したらimagedestroyでメモリを開放する必要があるでしょう。Daemon queue workers do not restart the framework before processing each job. Therefore, you should be careful to free any heavy resources before your job finishes. For example, if you are doing image manipulation with the GD library, you should free the memory with imagedestroy when you are done.

デーモンキューリスナのデプロイDeploying With Daemon Queue Listeners

デーモンキューワーカーは長時間起動するプロセスですので、リスタートしなければコードの変更が反映されません。そのためデーモンキューワーカーを使用しているアプリケーションをデプロイする簡単な方法は、スクリプトをデプロイしている間にワーカーをリスタートすることです。デプロイスクリプトに以下のコマンドを含めることで、全スクリプトを穏やかにリスタートできます。Since daemon queue workers are long-lived processes, they will not pick up changes in your code without being restarted. So, the simplest way to deploy an application using daemon queue workers is to restart the workers during your deployment script. You may gracefully restart all of the workers by including the following command in your deployment script:

php artisan queue:restart

このコマンドは存在しているジョブが失われないように、現在のジョブの処理が終了した後に、全キューワーカーへ穏やかに「終了する(die)」よう指示します。キューワーカーはqueue:restartコマンドが実行されると、終了することを思い出してください。ですから、キュージョブを自動的に再起動する、Supervisorのようなプロセスマネージャーを実行すべきでしょう。This command will gracefully instruct all queue workers to "die" after they finish processing their current job so that no existing jobs are lost. Remember, the queue workers will die when the queue:restart command is executed, so you should be running a process manager such as Supervisor which automatically restarts the queue workers.

注意: このコマンドは再起動のスケジュールするため、キャッシュシステムを利用しています。デフォルト状態ではAPCuはCLIコマンドのために動作しません。APCuを使用する場合はapc.enable_cli=1をAPCu設定に追加してください。Note: This command relies on the cache system to schedule the restart. By default, APCu does not work for CLI jobs. If you are using APCu, add apc.enable_cli=1 to your APCu configuration.

失敗したジョブの処理Dealing With Failed Jobs

物事は計画通りうまく行かない場合もありますので、キュージョブが失敗することも想定できます。でも心配ありません。最高な人たちも失敗はするものです! Laravelは指定した回数ジョブを再実行する便利な方法を用意しています。この回数実行してもうまく行かない場合は、failed_jobsテーブルに登録されます。失敗したジョブのテーブル名はconfig/queue.php設定ファイルで指定できます。Since things don't always go as planned, sometimes your queued jobs will fail. Don't worry, it happens to the best of us! Laravel includes a convenient way to specify the maximum number of times a job should be attempted. After a job has exceeded this amount of attempts, it will be inserted into a failed_jobs table. The name of the table can be configured via the config/queue.php configuration file.

failed_jobsテーブルのマイグレーションを生成するにはqueue:failed-tableコマンドを実行して下さい。To create a migration for the failed_jobs table, you may use the queue:failed-table command:

php artisan queue:failed-table

キューリスナを実行時にqueue:listenコマンドに--triesスイッチを使い、ジョブの最大試行回数を指定することもできます。When running your queue listener[#running-the-queue-listener], you may specify the maximum number of times a job should be attempted using the --tries switch on the queue:listen command:

php artisan queue:listen connection-name --tries=3

ジョブ失敗イベントFailed Job Events

キュージョブが失敗した時に呼び出されるイベントのリスナを登録したい場合は、Queue::failingメソッドを使って下さい。このイベントはメールかHipChatであなたのチームに通知するのに便利でしょう。例としてLaravelに含まれているAppServiceProviderにこのイベンのコールバックを追加してみましょう。If you would like to register an event that will be called when a queued job fails, you may use the Queue::failing method. This event is a great opportunity to notify your team via e-mail or HipChat[https://www.hipchat.com]. For example, we may attach a callback to this event from the AppServiceProvider that is included with Laravel:

<?php

namespace App\Providers;

use Queue;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションサービスの初期起動処理
     *
     * @return void
     */
    public function boot()
    {
        Queue::failing(function (JobFailed $event) {
            // $event->connectionName
            // $event->job
            // $event->data
        });
    }

    /**
     * サービスプロバイダー登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

ジョブクラスのfailedメソッドFailed Method On Job Classes

更に細かくコントロールするために、failedメソッドをキュージョブクラスへ直接定義することもできます。ジョブが失敗した時に特定のジョブアクションを実行できるようにできます。For more granular control, you may define a failed method directly on a queue job class, allowing you to perform job specific actions when a failure occurs:

<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendReminderEmail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    /**
     * ジョブの実行
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function handle(Mailer $mailer)
    {
        //
    }

    /**
     * 失敗したジョブの処理
     *
     * @return void
     */
    public function failed()
    {
        // ジョブが失敗した時に呼び出される
    }
}

失敗したジョブの再実行Retrying Failed Jobs

failed_jobsデータベーステーブルに挿入された、失敗したジョブを全部確認したい場合はqueue:failed Arisanコマンドを利用します。To view all of your failed jobs that have been inserted into your failed_jobs database table, you may use the queue:failed Artisan command:

php artisan queue:failed

queue:failedコマンドにジョブIDを指定すれば、接続、キュー、失敗した時間がリストされます。ジョブIDは失敗したジョブを再実行する場合にも使用します。たとえばIDが5の失敗したジョブを再実行するには、以下のコマンドを実行します。The queue:failed command will list the job ID, connection, queue, and failure time. The job ID may be used to retry the failed job. For instance, to retry a failed job that has an ID of 5, the following command should be issued:

php artisan queue:retry 5

失敗したジョブをすべて再試行するには、queue:retryでIDの代わりにallを指定します。To retry all of your failed jobs, use queue:retry with all as the ID:

php artisan queue:retry all

失敗したジョブを削除するにはqueue:forgetコマンドを使います。If you would like to delete a failed job, you may use the queue:forget command:

php artisan queue:forget 5

失敗したジョブを全部消去するにはqueue:flushコマンドを使用します。To delete all of your failed jobs, you may use the queue:flush command:

php artisan queue:flush

章選択

設定

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

ヘッダー項目移動

キーボード操作