问题描述
我正在学习Laravel,他正在一个运行Horizon的项目中学习工作.我被困在一个地方,需要一次又一次地做几次相同的工作.
I am learning Laravel, working on a project which runs Horizon to learn about jobs. I am stuck at one place where I need to run the same job a few times one after one.
这是我目前正在做的事情
Here is what I am currently doing
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Subscriptions;
class MailController extends Controller
{
public function sendEmail() {
Subscriptions::all()
->each(function($subscription) {
SendMailJob::dispatch($subscription);
});
}
}
这很好用,除了它可以跨多个工人运行作业,而且顺序不保证.有什么方法可以依次运行作业吗?
This works fine, except it runs the job's across several workers and not in a guaranteed order. Is there any way to run the jobs one after another?
推荐答案
您正在寻找的是工作链.
What you are looking for, as you mention in your question, is job chaining.
ProcessPodcast::withChain([
new OptimizePodcast,
new ReleasePodcast
])->dispatch();
所以在上面的示例中
$mailJobs = Subscriptions::all()
->map(function($subscription) {
return new SendMailJob($subscription);
});
Job::withChain($mailJobs)->dispatch()
应该给出预期的结果!
更新
如果您不想使用初始作业进行链接(如上面的文档示例中所示),则应该能够创建一个具有use Dispatchable;
的空Job
类.那你可以用我上面的例子
If you do not want to use an initial job to chain from (like shown in the documentation example above) you should be able to make an empty Job
class that that has use Dispatchable;
. Then you can use my example above
这篇关于Laravel-按顺序运行作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!