DEV Community

Mohamed Said
Mohamed Said

Posted on • Originally published at divinglaravel.com

5 1

Running a task after the response is sent

Normally, if you want to run a task and don't want the user to wait until it's done you'd dispatch a queued job. However, sometimes that task is really simple and short that putting it in a queue might be an overkill.

Using Laravel, you can run such tasks after sending the response to the user. It works by keeping the PHP process alive to run the tasks after closing the connection with the browser. You can do that using:

  • Terminable Middleware.
  • Terminating callbacks (e.g. App::terminating(function(){ }))
  • Job::dispatchAfterResponse() using Laravel v6.14.0 or higher.

If you have a job called ClearCache, you can run it after the response is sent like this:

function store(Response $response)
{
 // Do some work

 ClearCache::dispatchAfterResponse();  

 return view('success');
}

Remember, this is only a good idea if the task is really short. For long running tasks, dispatching to queue is recommended.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay