1

我正在尝试在 foreach 循环中调度 Laravel 作业。但问题是,当我在循环内调度作业时,有时它会在作业完成之前完成。我想要的是工作应该一个一个地完成。就像发生在链方法中一样。但是我如何在 foreach 循环中链接相同的工作?这可能吗?

foreach ($consignments as $consignment) {
     CalculateSingleConsignment::dispatch($consignment, $total_consignments, $i, $user_id, $notify)->onQueue('invoice');
     $i++;
}
4

1 回答 1

3

您可以构造要链接的数组,而不是在循环中分派实际作业:

$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'));

于 2021-01-21T07:15:53.813 回答