2025-12-11 11:11:56 +08:00
|
|
|
|
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;
|
2025-12-13 11:25:59 +08:00
|
|
|
|
using ZR.Service.mes.andon.Iservice;
|
2025-12-11 11:11:56 +08:00
|
|
|
|
|
|
|
|
|
|
namespace ZR.Service.mes.andon
|
|
|
|
|
|
{
|
|
|
|
|
|
public class ScheduledBackgroundService:BackgroundService
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly ILogger<ScheduledBackgroundService> _logger;
|
|
|
|
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
2025-12-13 11:26:45 +08:00
|
|
|
|
private readonly TimeSpan _interval = TimeSpan.FromMinutes(5);//定时5分钟执行一次
|
2025-12-11 11:11:56 +08:00
|
|
|
|
|
|
|
|
|
|
public ScheduledBackgroundService(
|
|
|
|
|
|
ILogger<ScheduledBackgroundService> 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
|
|
|
|
|
|
{
|
2025-12-13 11:25:59 +08:00
|
|
|
|
_logger.LogInformation($"开始执行安灯超时上报定时任务: {DateTime.Now:HH:mm:ss}");
|
|
|
|
|
|
// 核心:创建作用域,获取Scoped服务
|
|
|
|
|
|
using (var scope = _scopeFactory.CreateScope())
|
|
|
|
|
|
{
|
|
|
|
|
|
// 获取你的报警业务服务(Scoped生命周期)
|
|
|
|
|
|
var alarmService = scope.ServiceProvider.GetRequiredService<AndonAlarmRecordService>();
|
|
|
|
|
|
// 执行你的自动超时上报逻辑
|
|
|
|
|
|
var result = alarmService.AlarmReportAuto();
|
|
|
|
|
|
_logger.LogInformation($"定时任务执行完成,结果:{result.Msg}");
|
|
|
|
|
|
}
|
2025-12-11 11:11:56 +08:00
|
|
|
|
_logger.LogInformation($"定时任务完成");
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
_logger.LogError(ex, "定时任务执行异常");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 等待指定间隔
|
2025-12-13 11:25:59 +08:00
|
|
|
|
// Task.Delay增加取消令牌检查,避免任务卡住
|
|
|
|
|
|
if (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
|
{
|
|
|
|
|
|
await Task.Delay(_interval, stoppingToken);
|
|
|
|
|
|
}
|
2025-12-11 11:11:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
_logger.LogInformation("定时后台服务停止");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|