Search code examples
c#pollyretry-logic

Implementing retry logic with Polly library with no exception handling repeatedly


how to implement retry logic using polly to retry executing a function forever with some delay but handle no exception. the scenario is to get status information repeatedly but there is no expected exception.


Solution

  • Polly is not designed as a Cron-job tool and intentionally does not target that use case. Polly's retry focus is on the resilience of an individual operation (retrying until it succeeds) rather than repeatedly invoking things that do succeed).


    For other options (if useful):

    If the delay between executions is sufficient that you would like to release execution resources (thread or stack) between executions, consider:


    If the delay is sufficiently small (say every 5 seconds) that it is not worth releasing and re-obtaining execution resources, you could simply use an infinite loop with a delay. For example, if async:

    while (true)
    {
        // Do my repeated work
    
        await Task.Delay(TimeSpan.FromSeconds(5));
    }
    

    If you want cancellation (to end a program gracefully), of course you can extend this with cancellation:

    // for some CancellationToken cancellationToken
    while (!cancellationToken.IsCancellationRequested)
    {
        // Do my repeated work
    
        await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
    }
    

    One advantage of a periodic job scheduler such as HangFire is that if one of the executions crashes, the next scheduled invocation will still run. Whatever your solution, you should consider what you want to happen if one execution of the periodic job fails.