Fail a job with conditional retry

Yes, sure you can.

I do use something like this on my projects…

I don’t remember since which version it was available, but, on the current versions there is the PerformContext that you can inject in your jobs. It will allow you to access the running job context.

Just put it as a parameter in your job method, then, when queuing or scheduling the job, just pass null in it’s place, it will be injected upon job starts… (Don’t know if it requires any external activator, 'cos in all projects that i ever used hangfire, it was using Dependency Injection through some IoC Container).

Then, with the PerformContext instance inside your job, you can conditionally exhaust your job retries achieving the behavior that you want, so, you still can use the AutomaticRetryAttribute alongside with this…

To do this you may set the job RetryCount parameter to a number higher than your system ever could use… ex: 9999.

So, for example:

public class DummyJobsClass{
	// A RetryCount number that your system should never allow!
	public const int ExhaustRetryCounts = 9999;
	
	[AutomaticRetry(Attempts = 10)]
	public void MyDummyJobMethod(Guid someArgument, string anotherOne, PerformContext performContext){
		
		// ...

		if(true == SomeConditionThatJobMustNotRetry){
			// Set the job RetryCount to a Number that is 'Never Allowed' in your system...
			performContext.SetJobParameter("RetryCount", ExhaustRetryCounts);
			// Throw some exception to exit the Job and have a nice reason on your Dashboard... 
			throw new Exception("Houston, we have found an Alien! Never get back here!");
		}

		// ...
	}
}

Hope it helps…

Ahh one last tip:
_To be easy, and improve readability, i do use an Extension Method created in my projects on the PerformContext type, nicelly called ExaustJobRetries accepting a Reason parameter… _

2 Likes