Laravelでキュー/ジョブの環境を用意する (DB)
前提知識
ジョブ: 何らかの処理
キュー: ジョブを並ばせる列
- 保存先をドライバーと呼ぶ
- DB, SQS, Redisと選べる
ディスパッチ: ジョブをキューに送ること
ワーカー: キューの中のジョブに対する処理するプロセス
キューを用意する
php artisan queue:table php artisan migrate
今回はローカルのデータベースをキューの代わりに使う
ジョブを定義する
php artisan make:job SendReminderEmail
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class SendReminderEmail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { // } }
Route::get('/', 'PostsController@index', function() { $log = (new SendReminderEmail)->delay(10); dispatch($log); return 'ユーザー登録完了を通知するメールを送信しました。'; });
- 10秒後にSendReminderEmailインスタンスを実行するというジョブをキューに登録する
ワーカーの起動
php artisan queue:work