You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
3.2 KiB
C#

using NewLife.Threading;
using WorkerSynReport.Data;
namespace WorkerSynReport;
public class Alr111Worker:BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<AlrWorker> _logger;
private bool run = false;
TimerX? _timer;
public Alr111Worker(ILogger<AlrWorker> 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<IDb111Context>();
var entity = dbContextLocal.Query<WarnTable>().TakePage(1, 1000)
.OrderBy(x => x.Id)
.ToList();
var ids = entity.Select(x => x.Id).ToList();
dbContextLocal.Delete<WarnTable>(x => ids.Contains(x.Id));
foreach (var eTable in entity)
{
var wInfo = dbContextLocal.Query<WarnTableInfo>()
.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<WarnTableInfo>(x => x.CreateTime < DateTime.Today.AddDays(-7));
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
finally
{
run = false;
}
}
_logger.LogInformation("跑警告结束");
}
}