ChargingFlowMonitorBackgroundService.cs 1.42 KB
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Rcs.Application.Services;

namespace Rcs.Infrastructure.Services;

/// <summary>
/// 自动充电巡检后台服务,用于周期触发充电流程兜底处理。
/// </summary>
public class ChargingFlowMonitorBackgroundService : BackgroundService
{
    private readonly ILogger<ChargingFlowMonitorBackgroundService> _logger;
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly TimeSpan _interval = TimeSpan.FromSeconds(5);

    public ChargingFlowMonitorBackgroundService(
        ILogger<ChargingFlowMonitorBackgroundService> logger,
        IServiceScopeFactory scopeFactory)
    {
        _logger = logger;
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var chargingFlowService = scope.ServiceProvider.GetRequiredService<IChargingFlowService>();
                await chargingFlowService.ReconcileAsync(stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Charging flow reconcile failed");
            }

            await Task.Delay(_interval, stoppingToken);
        }
    }
}