Skip to content

Commit

Permalink
chore: make sure that data is always freshed during an even hour
Browse files Browse the repository at this point in the history
  • Loading branch information
alsami committed Dec 23, 2020
1 parent d223a16 commit e1ae913
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions src/Covid19Api.Worker/DataRefreshWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit e1ae913

Please sign in to comment.