5

From this post:

How do I get the current attempt number on a background job in Hangfire?

It is possible to get the retry count by using the magic string "RetryCount".

public void SendEmail(PerformContext context, string emailAddress)
{
   string jobId = context.BackgroundJob.Id;
   int retryCount = context.GetJobParameter<int>("RetryCount");
   // send an email
}

How about if I need to get the total retry number? Can I use something like:

int retries = context.GetJobParameter<int>("Retries");

Or how can I get that info from the "PerformContext" (if possible at all)?

I need the total retries defined thus I can perform some tasks on the last retry.

Pieter Alberts
  • 829
  • 1
  • 7
  • 23
msola
  • 119
  • 1
  • 7

1 Answers1

2

If you are using AutomaticRetryAttribute to define the number of retry attempts on a method then something like the following will work:

var retryAttempts = context.BackgroundJob.Job.Method.GetCustomAttributes(typeof(AutomaticRetryAttribute), false)
    .Cast<AutomaticRetryAttribute>()
    .Select(a => a.Attempts)
    .FirstOrDefault();

If the attribute is not present then this will return 0. This will not help if the maximum number of retries is set globally or modified in the attribute at a later date.

wolfyuk
  • 746
  • 1
  • 8
  • 26