问题描述
我的Laravel应用程序具有排队的事件侦听器,我有还将cronjob设置为每分钟运行 schedule:run
.
My Laravel application has a queued event listener and I have also set up the cronjob to run schedule:run
every minute.
但是我不知道如何在后台持久运行 php artisan queue:worker
命令.我发现此线程投票最多的方法:
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?
推荐答案
从Laravel 5.7开始,有一个新的队列命令在空时停止工作:
Since Laravel 5.7, there's a new queue command to stop working when empty:
php artisan queue:work --stop-when-empty
由于这主要是用于电子邮件或少量小型工作,因此我将其放在cronjob上,以便每分钟运行一次.我说这并不是每分钟超过100个工作的解决方案,但可以处理我的电子邮件.发送电子邮件的时间大约每分钟5秒,具体取决于发送的电子邮件数量或工作量.
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
中,更改:protected $ signature ='emails:work';
- 在
handle()
方法中,添加:
- 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,
]);
- 每分钟安排您的命令:
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:work')->everyMinute();
// you can add ->withoutOverlapping(); if you think it won't finish in 1 minute
}
- 更新您的cronjobs:
* * * * * /usr/local/bin/php /home/username/project/artisan schedule:run > /dev/null 2>&1
php artisan queue:work --stop-when-empty
这篇关于如何在共享主机上运行队列工作器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!