51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
|
|
using HealtRegistry.Models;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace HealtRegistry.Services;
|
|
|
|
public class HealthTimeoutService : BackgroundService
|
|
{
|
|
private readonly IHealthService _healthService;
|
|
private readonly IOptionsMonitor<ServicesConfiguration> _servicesConfiguration;
|
|
private readonly ILogger<HealthTimeoutService> _logger;
|
|
|
|
public HealthTimeoutService(
|
|
IHealthService healthService,
|
|
IOptionsMonitor<ServicesConfiguration> servicesConfiguration,
|
|
ILogger<HealthTimeoutService> logger
|
|
)
|
|
{
|
|
_healthService = healthService;
|
|
_servicesConfiguration = servicesConfiguration;
|
|
_logger = logger;
|
|
}
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
var now = DateTimeOffset.Now;
|
|
foreach (var service in _healthService.ServiceHealthes)
|
|
{
|
|
if (!service.Value.Healthy) continue;
|
|
|
|
var serviceConfiguration = _servicesConfiguration.CurrentValue.Services.TryGetValue(service.Key, out var configuration)
|
|
? configuration
|
|
: null;
|
|
|
|
if (serviceConfiguration is not null &&
|
|
now - service.Value.LastUpdated > serviceConfiguration.Timeout)
|
|
{
|
|
_logger.LogInformation("Service {ServiceName} is timed out", service.Key);
|
|
_healthService.SetServiceHealth(service.Key, false);
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
await Task.Delay(1000, stoppingToken);
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
} |