using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Schaad.OpenData.Hydrology; public sealed class HydrologyRefreshService( HydrologyRefresher 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 hydrology 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, "Hydrology refresh failed"); } await Task.Delay(CheckInterval, stoppingToken); } } }