Microsoft's example for a forever/continous IHostedService
at Implement background tasks in microservices with IHostedService and the BackgroundService class uses while
+Task.Delay
'pattern'.
This illustrated with a code snippet that a simplified version is just below.
public class GracePeriodManagerService : BackgroundService
(...)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//Do work
await Task.Delay(timeSpan, stoppingToken);
}
}
This pattern suffers from a creeping shift - the work is done every timeSpan
+how_long_work_took
. Even when how_long_work_took
is very small over a period of time it adds up.
I would like to avoid calculating timeSpan
based on how long work
took.
What would a robust solution be to run every fixed_amount_of_time?.
Thinking out loud: If I use a task scheduler library, like HangFire, inside ExecuteAsync
does using IHostedService
/BackgroundService
even make sense any more?
A bonus would be to be able to run a task at a point in time (e.g. at midnight)