Adding new jobs to batches

Tags: #<Tag:0x00007faff688d4e0>

Is it possible to add jobs to existing batches (given a BatchId), after that batch has been initially setup?

E.g.

var batchId = BatchJob.StartNew(x =>
{
for (var i = 0; i < jobsCount; i++)
{
x.Enqueue(() => new MyJob().Run());
}
});

When MyJob.Run() executes, I want to create a set of jobs assigned to that same batch… And need to ensure that batch has completed, before continuing with the next batch.

Oh dear, I’m afraid that currently you can only execute that extra work in the MyJob.Run method, since it’s not possible to add background jobs to an existing batch. By the way, it’s better to use the generic method, instead of creating a job class instance:

batch.Enqueue<MyJob>(x => x.Run());

Thanks for that - that’s sort of what I’d expected you to say… I can move the BatchJob setup to its own long-running service, and calculate the number of jobs required at that point.

@Kevin_Blake, starting from Hangfire.Pro 2.0.0-beta2 it’s possible to add jobs and other batches into an existing batch:

BatchJob.Attach(batchId, batch => 
{
    foreach (var record in records)
    {
        batch.Enqueue(() => ProcessRecord(ListId, record.Id)));
    }
});
1 Like