Cancel the job continuations if exception occur

My job adds the continuation to itself. Also my job may fail with exception, and then it will be retried automatically, exactly as expected.

However during the retry it will again create the same continuation, and if the job happens to complete this time - both continuations will run, which is not desirable.

I can of course add all continuations to the list and only add them after all try-catches so that there is only one continuation scheduled, but it adds some complexity to the code.

Are there any good ways for fixing this behavior?

I assume you’ve figure this out by now, but for posterity’s sake, there’s an additional argument you can provide to the ContinueJobWith method call:

public static string ContinueJobWith(
    [NotNull] string parentId, 
    [NotNull][InstantHandle] Expression<Action> methodCall, 
    JobContinuationOptions options /* <-- this argument */)

JobContinuationOptions is an enum:

public enum JobContinuationOptions
{
    OnAnyFinishedState = 0,
    OnlyOnSucceededState = 1,
    OnlyOnDeletedState = 2
}

Using JobContinuationOptions.OnlyOnSucceededState will limit the continuation job to only running if the parent job completed successfully.

There is a subtle difference between job execution and job try execution, and this parameter only refers to the whole job with all its retries.

In my case, if the job fails several times, retries several times, and then eventually succeeds, and if I was calling ContinueJobWith with OnlyOnSucceededState on every retry, it would call all these continuations after successful job run.

Anyways, I had to write the custom hangfire filter in which I clean all continuations in case job retry (not the whole job) fails with exception. Not very elegant, but works in my case.