Search code examples
c#pollyretry-logicexponential-backoffpolicywrap

Polly C# retry exponentially for 3 tries then switch to retrying every hour


I am trying to use polly to construct a policy that can retry exponentially for n tries and then switch to retrying every 1 hour. Can this be achieved?

I tried policy Wrap but did not get the desired results


Solution

  • This should be possible to achieve with overloads accepting custom sleepDurationProvider. For example something like the following:

    var waitAndRetry = Policy
        .Handle<SomeException>()
        .WaitAndRetry(4, retryAttempt => retryAttempt switch // or WaitAndRetryForever
        {
            <= 3 => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), // for example n == 3
            _ => TimeSpan.FromHours(1)
        });