Issues with queues Laravel (asynchronous functions)

I created a Laravel function using queues but it seems that it isn't working because I created 10 pdf files using foreach, and also a function with queues, but the execution time is the same.

This is my function with queues:

$encuesta = Encuesta::where('id', $request->interes_id)
        ->with('empresa')
        ->first();

$personas = EncuestaPuntaje::where('encuesta_id', $request->interes_id)
        ->with('persona')
        ->with('puntajes.carrera')
        ->get();

if ($personas->isEmpty()) {
    return response()->json(['error' => 'No hay encuestas resueltas.'], 401);
} else {
    foreach ($personas as $p) {
        PDF::dispatchNow($p['persona'], $p['puntajes'], $encuesta['empresa']['nombre']);
    }

And this is my job:

public function handle()
{
    $carreras = Carrera::where('estado', 1)->orderBy('nombre', 'asc')
        ->get();

    $content = \PDF::loadView('reporte_interes', array('carreras' => $carreras, 'persona' => $this->persona, 'puntajes' => $this->puntajes))->output();

    $name = 'PDF/'.$this->empresa . '/INTERESES/' . $this->persona->nombres . '' . $this->persona->apellido_paterno . '.pdf';
    \Storage::disk('public')->put($name,  $content);
}

Here I generate 1 file:

enter image description here

And here I generate 10 files:

enter image description here

It is my first time using queues in Laravel and I wanted the times to be the same.

Upvotes: 0

Views: 157

Answers (1)

Don't Panic
Don't Panic

Reputation: 14520

The code you've shown is using dispatchNow(), but if you check the docs:

If you would like to dispatch a job immediately (synchronously), you may use the dispatchNow method. When using this method, the job will not be queued and will be run immediately within the current process

So dispatchNow is really not using queues at all. The job runs immediately and holds up your front end (the controlling process), until it is done, just the same as if you weren't using queues at all. You won't see any speed improvement.

Switch to using normal dispatching, and the process will be deferred, and run asynchronously, in parallel but separate from your main task, allowing it to continue immediately. Your main task will seem to finish much quicker, while in the background, the job is still running.

PDF::dispatch($p['persona'], ...

Upvotes: 1

Related Questions