如何循环调度链式作业?
How to dispatch a chained job in a loop?
我正在尝试在 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'));
我正在尝试在 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'));