Saturday, 2 December 2017

Using laravel Queues on shared hosting: A simple guide

If you're like me (and every other developer), you must have now realized the importance of using queues. Queues give you the power of async programming by allowing you run some important (any) task in the background.

Let's think about it this way: in a typical web app, we have the usual request-response cycle where your user sends a request to your server, your server processes the request, when it's done, it sends back a response to the user (browser) - this is the way it works. 

Now, there is no problem with this, except in a situation whereby during the request, your server needs to send mails (to one or more users), generate pdf files, make calls to 4 other external APIs and so on, that's getting too long right?

In a typical request-response, your user has to wait until your server is done with all those tasks before they get a feedback. These tasks can take anywhere between 30 seconds to forever, which is a lot, if you ask me.

Instead, how about, we do it such that user sends request, and get feedback immediately? cool right? But I hear you ask, what happens to our tasks? Well, we are not discarding them, we are just pushing them to background workers, so our users do not have to wait.

Setting up queue workers with laravel is quite easy, on your local server and when deployed to a cloud hosting environment, but not quite so when deploying to a shared hosting environment. However, there's a simple solution for this as well.

For this post, I'm assuming you already have your queue configured (the drivers and all).

We will be combining the power of Laravel Task SchedulingLaravel Queues and Cron Jobs


Steps:

  • Set up a cron job on your server like such: * * * * * php /path-to-project/artisan schedule:run >> /dev/null 2>&1
    The above is telling your cron to run once every minute. So, once every minutes, it runs your scheduled laravel task.
  • Now, in your code, in the Kernel.php file: App\Console\Kernel, add the following line:  $schedule->command('queue:work --tries=3')
    ->cron('* * * * * *')
    ->withoutOverlapping();

    So that your Kernel.php now looks like this: 
  • You should be all set up now. Dispatch new jobs to your queue, and see them all executed every minute.
Quite easy, eh!
That'd be all from me, for now. Bye!

1 comment:

Say something...