My Laravel application has a queued event listener and I have also set up the cronjob to run schedule:run
every minute.
But I don't know how I can run the php artisan queue:worker
command persistently in the background. I found this thread where it was the most voted approach:
$schedule->command('queue:work --daemon')->everyMinute()->withoutOverlapping();
However, on a different thread some people complained that the above-mentioned command creates multiple queue worker.
How can I safely run a queue worker?
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.
php artisan make:command SendContactEmails
SendContactEmails.php
, change: protected $signature = 'emails:work';
handle()
method, add: return $this->call('queue:work', [
'--queue' => 'emails', // remove this if queue is default
'--stop-when-empty' => null,
]);
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:work')->everyMinute();
// you can add ->withoutOverlapping(); if you think it won't finish in 1 minute
}
* * * * * /usr/local/bin/php /home/username/project/artisan schedule:run > /dev/null 2>&1
Source
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With