using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Schaad.OpenData.Traffic; public sealed class TrafficRefreshService( TrafficRefresher refresher, IOptions options, ILogger logger) : BackgroundService { private static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(15); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { await refresher.LoadCacheAsync(stoppingToken); } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Could not load the traffic cache"); } while (!stoppingToken.IsCancellationRequested) { try { if (refresher.IsRefreshDue(options.Value.RefreshInterval)) { await refresher.RefreshAsync(stoppingToken); } await refresher.BuildMissingGeometryAsync(stoppingToken); } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Traffic refresh failed"); } await Task.Delay(CheckInterval, stoppingToken); } } }