LaravelのQueueを実行するには、一般的にはartisanコマンドを使います。
php artisan queue:work
でも状況によっては、artisanコマンド以外でqueueに積まれたタスクを実行したいときもあると思います。supervisorが使えないとか…。
そんなときにWebアクセスからQueueの実行をする方法を紹介します。
LaravelのQueueWorker
artisan queueコマンドではQueueWorker経由で実行されていて、実質こいつがQueueの実行を司っているのがわかります。
Illuminate/Queue/Worker.php
<?php
namespace Illuminate\Queue;
use Exception;
use Throwable;
use Illuminate\Support\Carbon;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\DetectsLostConnections;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Illuminate\Contracts\Cache\Repository as CacheContract;
class Worker
{
use DetectsLostConnections;
・・・
WorkerをWebアクセスから呼び出す
ControllerからWorkerを呼び出して、Queueに積まれたタスクを実行します。
app/Http/Controllers/QueueWorkerController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Worker;
use Illuminate\Queue\WorkerOptions;
class QueueWorkerController extends Controller
{
private $worker;
public function __construct(Worker $worker)
{
$this->worker = $worker;
}
public function work()
{
$connection = $this->getConnection();
$this->queueWorker->runNextJob(
$this->getConnection(),
$this->getQueue($connection),
new WorkerOptions()
);
return ['process complete'];
}
private function getConnection(): string
{
return config('queue.default');
}
private function getQueue(string $connection): string
{
return config("queue.connections.{$connection}.queue", 'default');
}
}
これで、アクセスするとQueueに積まれたタスクを1回実行してくれます。