shgx_tz_mom/ZR.Service/mes/andon/ScheduledBackgroundService.cs
2026-01-06 08:49:12 +08:00

78 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Aliyun.OSS;
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<ScheduledBackgroundService> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly TimeSpan _interval = TimeSpan.FromMinutes(5);//定时5分钟执行一次
private int lightAutoCount = 0;
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
{
_logger.LogInformation($"开始执行安灯超时上报定时任务: {DateTime.Now:HH:mm:ss}");
// 核心创建作用域获取Scoped服务
using (var scope = _scopeFactory.CreateScope())
{
// 获取你的报警业务服务Scoped生命周期
var alarmService = scope.ServiceProvider.GetRequiredService<IAndonAlarmRecordService>();
// 执行报警信息自动超时上报逻辑
var result = alarmService.AlarmReportAuto();
//
//if (lightAutoCount < 4)
//if(true)
//{
// var result2 = alarmService.InitAlarmLightStates();
// lightAutoCount++;
//}
var result2 = alarmService.InitAlarmLightStates();
_logger.LogInformation($"定时任务执行完成,结果:{result.Msg}");
}
_logger.LogInformation($"定时任务完成");
}
catch (Exception ex)
{
_logger.LogError(ex, "定时任务执行异常");
}
// 等待指定间隔
// Task.Delay增加取消令牌检查避免任务卡住
if (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(_interval, stoppingToken);
}
}
_logger.LogInformation("定时后台服务停止");
}
}
}