From e1ae9131816ea151ae82eecbf89503ae33c3bf72 Mon Sep 17 00:00:00 2001 From: alsami Date: Wed, 23 Dec 2020 14:14:35 +0100 Subject: [PATCH] chore: make sure that data is always freshed during an even hour --- src/Covid19Api.Worker/DataRefreshWorker.cs | 31 +++++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) 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()