How do I conditionally control retry behavior of the current job?

Hi Guys,

I’m trying out Hangfire and am quite interested in its capability :slight_smile: I have a question here for my “unique” usage :blush::

Is there anyway I can conditionally control retry behavior of the current job, inside the logic part of the job?

For example I’d like to execute a job like this (see questions in comments begin with Q:):

public class AppendFileJob
{
    public void AppendToFile(string content, string filePath)
    {
        if (string.IsNullOrEmpty(content))
        {
            // Invalid input, 
            // Q: How to set the job to be not retried before exit?
            throw new ArgumentNullException("content");
        }
        if (!File.Exists(filePath))
        {
            // File doesn't exist now, but may be in the next few reties
            
            // Q: How do I get currentRetryNumber?
            var currentRetryNumber = ?;
            if (currentRetryNumber == 5) 
            {
                // Q: How to set the job to retry 3 more times with customized interval?
            }
            else
            {
                // Exit with the normal retry
                throw new FileNotFoundException(
                    string.Format("retry {0} more times", 8 - currentRetryNumber), filePath);
            }
        }
        File.AppendAllLines(filePath, new[] { content });
    }
}

Many Thanks!

1 Like