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.

105 lines
3.2 KiB
C#

5 months ago
using System.Collections.Immutable;
using NewLife.Log;
10 months ago
using NewLife.Threading;
5 months ago
using WorkerSynReport.Data;
10 months ago
namespace WorkerSynReport;
5 months ago
public class AlrWorker:BackgroundService
10 months ago
{
private readonly IServiceScopeFactory _scopeFactory;
5 months ago
private readonly ILogger<AlrWorker> _logger;
private bool run = false;
10 months ago
TimerX? _timer;
5 months ago
public AlrWorker(ILogger<AlrWorker> logger, IServiceScopeFactory scopeFactory)
10 months ago
{
_logger = logger;
this._scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
5 months ago
_timer ??= new TimerX(DoPlc, "", 100, 1000);
10 months ago
_timer.Async = true;
5 months ago
10 months ago
}
private void DoPlc(Object state)
{
5 months ago
_logger.LogInformation("开始跑警告");
if (!run)
{
try
{
run = true;
using var scope = _scopeFactory.CreateScope();
var services = scope.ServiceProvider;
using IDbContextLocal? dbContextLocal = services.GetService<IDbContextLocal>();
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;
}
}
10 months ago
5 months ago
_logger.LogInformation("跑警告结束");
10 months ago
}
}