How to run queue worker on shared hosting
Since Laravel 5.7, there's a new queue command to stop working when empty:
php artisan queue:work --stop-when-empty
As this is mostly just for emails or few small jobs, I put it on a cronjob to run every minute. This isn't really a solution for more than 100 jobs per minute I'd say, but works for my emails. This will run about 5 seconds every minute just to send emails, depending on how many emails or how big the job.
Steps
- Create new command:
php artisan make:command SendContactEmails
- In
SendContactEmails.php
, change:protected $signature = 'emails:work';
- In the
handle()
method, add:
return $this->call('queue:work', [ '--queue' => 'emails', // remove this if queue is default '--stop-when-empty' => null,]);
- Schedule your command every minute:
protected function schedule(Schedule $schedule){ $schedule->command('emails:work')->everyMinute(); // you can add ->withoutOverlapping(); if you think it won't finish in 1 minute}
- Update your cronjobs:
* * * * * /usr/local/bin/php /home/username/project/artisan schedule:run > /dev/null 2>&1
Processing All Queued Jobs & Then Exiting
The
--stop-when-empty
option may be used to instruct the worker to process all jobs and then exit gracefully. This option can be useful when working Laravel queues within a Docker container if you wish to shutdown the container after the queue is empty:
php artisan queue:work --stop-when-empty