3

I am trying to implement async job in laravel, so I can send email (using 3rd party API), but let user go in the frontend so request doesn't wait for email to be sent. I am using Laravel 6.18.

so I've created generic job with php artisan make:job EmailJob

I've set sleep for 60 seconds as a test of long email send.

then in my controller

   EmailJob::dispatchAfterResponse();
   return response()->json($obj,200);

In chrome console, I can see there is 200 response, however request is still no resolved, and there is no data returned, so my ajax/axios request still waits for full response, eventually it times out (60 seconds is too long), and produces error in frontend.

So question is, how to execute job after full response is sent ?

uneasy
  • 547
  • 1
  • 7
  • 17

2 Answers2

2

You have to change the queue driver and run queue:worker

The following 2 resources will help you

  1. https://laravel-news.com/laravel-jobs-and-queues-101
  2. https://laravel.com/docs/6.x/queues#connections-vs-queues
abSiddique
  • 11,647
  • 3
  • 23
  • 30
  • Thank you, just read it through. This adds a lot of overhead, as probably I would have to use database driver, and run jobs with `queue:worker` I am not sure how to automate that in production server. I want job to be executed right away, just not sync, seems there is no straight forward solution – uneasy Nov 10 '21 at 21:11
  • As far as I read the laravel-documentation the dispatchAfterResponse()-function should do exactly what uneasy needs, executing the job in background without having a queue-worker running. However it's not working for me neither, so I would be glad for a hint how to do it without queue – Witold Jan 18 '22 at 14:11
1

Just like in Terminable Middleware, this will only work if the Webserver has FastCGI implemented.

You can go that way, or you can do a Queue with Database driver, which is simpler to achieve than installing Redis. You would still need to have a running process to complete the jobs. (worker)

ijpatricio
  • 170
  • 7