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.
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:
- in classic ASP.NET, tools such as HangFire
- in .NET Core 2.1, Background tasks with hosted services
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.
.Handle<Exception>(e => false)
was incorrect; it would not multiple-invoke a successful task. The retry architecture of Polly is geared to retrying-to-achieve-success of a single operation, not repeatedly invoking things which have succeeded. My hunch is the Polly team are unlikely to extend Polly into being a cron-job tool as this starts to fall outside Polly's core focus on resilience - and there are other cron-job -type solutions available. Thanks though for the q, which helped clarify this dimension. –
Caban You would be better of using something that is meant for CRON jobs like Hangfire.
But in case you really want to do with Polly. Here is how you can do it.
await Policy
.HandleResult<bool>(c => c == false) //you can add other condition
.WaitAndRetryForeverAsync(i => TimeSpan.FromMinutes(i))
.ExecuteAsync(async () =>
{
await DoSomethingAsync();
return true; //return false to stop execution
});
https://github.com/App-vNext/Polly/wiki/Retry#retry-to-refresh-authorization
© 2022 - 2024 — McMap. All rights reserved.