Easy Way of Appending Jobs to a Batch's *Current* Chain? #35738
Replies: 4 comments 2 replies
-
I came up with a solution that works, but it isn't very eloquent.. // Step 1: Execute a first batch in parallel
$firstBatch = Bus::batch([
(new EnqueueMoreTestJobsJob())
]);
// Step 2: Execute a second batch in parallel, but only after $firstBatch
$secondBatch = null;
$firstBatch->then(function() use (&$secondBatch) {
$secondBatch = Bus::batch([
(new EnqueueEvenMoreTestJobsJob())
]);
$secondBatch->dispatch();
});
// Step 3: Keeping chaining etc etc This gets unwieldy when working with 5 chain items. Any tips for making this easier on the eyes? |
Beta Was this translation helpful? Give feedback.
-
I came across this whilst looking for a solution to a job in a Batch where i needed to prepend to the current chain in the batch but still maintain batchability
|
Beta Was this translation helpful? Give feedback.
-
Thank you @bretto36 for your solution. Is there a better way to append jobs and not prepend please ? |
Beta Was this translation helpful? Give feedback.
-
@squiaios I ended up coming up with a neater solution
But for appending.. that's quite tricky cause you'd technically just need to adjust the chain on the current job, but you wouldn't be able to let the job know there is another job added to the queue, so you progress metrics on the Batch in horizon would be wrong. In my example above i remove the existing chain from the current job and add it to the new next job If you didn't care about the progress stats then you can always just do $this->appendToChain(new Job()); If you DO care about the progress stats then i tinkered with this but couldn't quite nail it
|
Beta Was this translation helpful? Give feedback.
-
I'm using Batches on Laravel 8 - love'em! In the docs, it shows you how to use chains with them, too:
Chaining Batches
https://laravel.com/docs/8.x/queues#chains-within-batches
Appending Jobs to Batches
The docs even show a use case of appending more jobs to the batch from a "loader"-style job:
https://laravel.com/docs/8.x/queues#adding-jobs-to-batches
The Confusion
I was confused why my jobs were out of sync for admittedly way too long. I dug into what was happening, and it does make sense and isn't a bug.
Expectation
Actual Result
This does make sense, as the demo does show adding to the batch and not a chain. Although I did see some means of interacting with chains in the framework, I wasn't able to determine how to do that with batches.
Something like replacing
add
withchain
below would illustrate the goal:Anyone have a simple solution before I dig some more? Cheers.
Beta Was this translation helpful? Give feedback.
All reactions