Search code examples
asp.net-mvcscheduled-taskshangfire

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


There are some database operations I need to execute before the end of the final attempt of my Hangfire background job (I need to delete the database record related to the job)

My current job is set with the following attribute:
[AutomaticRetry(Attempts = 5, OnAttemptsExceeded = AttemptsExceededAction.Delete)]

With that in mind, I need to determine what the current attempt number is, but am struggling to find any documentation in that regard from a Google search or Hangfire.io documentation.


Solution

  • Simply add PerformContext to your job method; you'll also be able to access your JobId from this object. For attempt number, this still relies on magic strings, but it's a little less flaky than the current/only answer:

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