using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Schaad.OpenData.Weather; public sealed class WeatherRefreshService( WeatherRefresher refresher, IOptions options, ILogger logger) : BackgroundService { private static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(1); 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 weather cache"); } while (!stoppingToken.IsCancellationRequested) { try { if (refresher.IsRefreshDue(options.Value.RefreshInterval)) { await refresher.RefreshAsync(stoppingToken); } } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Weather refresh failed"); } await Task.Delay(CheckInterval, stoppingToken); } } }