using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ZR.Service.mes.andon.Iservice; namespace ZR.Service.mes.andon { public class ScheduledBackgroundService:BackgroundService { private readonly ILogger _logger; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeSpan _interval = TimeSpan.FromMinutes(5);//定时5分钟执行一次 public ScheduledBackgroundService( ILogger logger, IServiceScopeFactory scopeFactory) { _logger = logger; _scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation($"定时后台服务启动,执行间隔: {_interval.TotalMinutes}分钟"); // 延迟启动,等待应用完全初始化 await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); while (!stoppingToken.IsCancellationRequested) { try { _logger.LogInformation($"开始执行安灯超时上报定时任务: {DateTime.Now:HH:mm:ss}"); // 核心:创建作用域,获取Scoped服务 using (var scope = _scopeFactory.CreateScope()) { // 获取你的报警业务服务(Scoped生命周期) var alarmService = scope.ServiceProvider.GetRequiredService(); // 执行你的自动超时上报逻辑 var result = alarmService.AlarmReportAuto(); _logger.LogInformation($"定时任务执行完成,结果:{result.Msg}"); } _logger.LogInformation($"定时任务完成"); } catch (Exception ex) { _logger.LogError(ex, "定时任务执行异常"); } // 等待指定间隔 // Task.Delay增加取消令牌检查,避免任务卡住 if (!stoppingToken.IsCancellationRequested) { await Task.Delay(_interval, stoppingToken); } } _logger.LogInformation("定时后台服务停止"); } } }