我试图在foreach循环内调度Laravel作业。但问题是,当我在循环内调度作业时,有时它在作业队列完成之前就完成了。我想要的是工作应该一个接一个地完成。就像链式方法一样。但是我如何在foreach循环中链接相同的作业呢?这可能吗?
foreach ($consignments as $consignment) {
CalculateSingleConsignment::dispatch($consignment, $total_consignments, $i, $user_id, $notify)->onQueue('invoice');
$i++;
}
可以构造要链接的数组,而不是在循环中调度实际的作业:
$jobs = [];
foreach (array_values($consignments) as $i => $consignment) {
$jobs[] = new CalculateSingleConsignment($consignment, $total_consignments, $i, $user_id, $notify);
}
Bus::chain($jobs)->onQueue('invoice')->dispatch()
如果你想使用依赖注入,你可以这样构造你的作业:
app()->makeWith(CalculateSingleConsignment::class, compact('consignment', 'total_consignments', 'i', 'user_id', 'notify'));