diff --git a/src/Covid19Api.Worker/DataRefreshWorker.cs b/src/Covid19Api.Worker/DataRefreshWorker.cs index 550f4f8..c02f6d9 100644 --- a/src/Covid19Api.Worker/DataRefreshWorker.cs +++ b/src/Covid19Api.Worker/DataRefreshWorker.cs @@ -24,23 +24,46 @@ public DataRefreshWorker(IServiceProvider serviceProvider, protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + var nextRun = this.CalculateInitialExecutionTime(); while (!stoppingToken.IsCancellationRequested) { try { - await this.ProcessAsync(); + if (DateTime.UtcNow >= nextRun) + { + await this.ProcessAsync(); + + nextRun = this.CalculateNextRun(); + } } catch (Exception e) { this.logger.LogCritical(e, e.Message); } - var nextRun = DateTime.UtcNow.AddHours(4); + await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); + } + } - this.logger.LogInformation("Next run {nextRun}", nextRun.ToString("O")); + private DateTime CalculateInitialExecutionTime() + { + var currentTime = DateTime.UtcNow; + var minutesDiff = 60 - currentTime.Minute; + var nextExecution = currentTime.AddMinutes(minutesDiff).AddSeconds(-currentTime.Second); + this.logger.LogInformation("Next refresh run {nextRun}", nextExecution.ToString("O")); + return nextExecution; + } - await Task.Delay(TimeSpan.FromHours(4), stoppingToken); + private DateTime CalculateNextRun() + { + var nextExecution = DateTime.UtcNow.AddHours(4); + if (nextExecution.Day != DateTime.UtcNow.Day) + { + nextExecution = DateTime.UtcNow.Date.AddDays(1); } + + this.logger.LogInformation("Next refresh run {nextRun}", nextExecution.ToString("O")); + return nextExecution; } private async Task ProcessAsync()