How to make a background job run where it stopped when app pool was recycled?

I am starting a background task using ‘BackgroundJob.Enqueue(() => DoSomeLongProcess())’.

DoSomeLongProcess method contains a loop that has 200 iterations. If app pool recycled when the 100th iteration was running then hangfire is always re-running this method after the recycle. This means the iteration starts from the first iteration.

Is it possible to tell hangfire to re-start the task from where it left off?

You can make your method reentrant, by flushing the current number of iteration to the database and checking the existing one:

int current = Database.GetCurrentIteration(id);
for (current; current < total; current++)
{
    // Processing logic
    Database.SaveCurrentIteration(id, current);
}
1 Like