using NewLife.Threading; using WorkerSynReport.Data; namespace WorkerSynReport; public class Alr111Worker:BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private bool run = false; TimerX? _timer; public Alr111Worker(ILogger logger, IServiceScopeFactory scopeFactory) { _logger = logger; this._scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _timer ??= new TimerX(DoPlc, "", 100, 1000); _timer.Async = true; } private void DoPlc(Object state) { _logger.LogInformation("开始跑警告"); if (!run) { try { run = true; using var scope = _scopeFactory.CreateScope(); var services = scope.ServiceProvider; using IDb111Context? dbContextLocal = services.GetService(); var entity = dbContextLocal.Query().TakePage(1, 1000) .OrderBy(x => x.Id) .ToList(); var ids = entity.Select(x => x.Id).ToList(); dbContextLocal.Delete(x => ids.Contains(x.Id)); foreach (var eTable in entity) { var wInfo = dbContextLocal.Query() .Where(x => x.AlarmId == eTable.AlarmId) .Where(x => x.Status == 1).FirstOrDefault(); if (eTable.Status == 1) { if (wInfo == null) { WarnTableInfo warnTableInfo = new() { AlarmId = eTable.AlarmId, Status = eTable.Status, CreateTime = eTable.CreateTime, UpdateTime = eTable.UpdateTime, Num = eTable.Num, CnInfo = eTable.CnInfo, OtherInfo = eTable.OtherInfo }; dbContextLocal.Insert(warnTableInfo); } } else { if (wInfo != null) { dbContextLocal.TrackEntity(wInfo); wInfo.UpdateTime = DateTime.Now; wInfo.Status = eTable.Status; dbContextLocal.Update(wInfo); } } } dbContextLocal.Delete(x => x.CreateTime < DateTime.Today.AddDays(-7)); } catch (Exception e) { _logger.LogError(e.Message); } finally { run = false; } } _logger.LogInformation("跑警告结束"); } }