SystemBackgroudService.cs
4.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using HHECS.DAQShared.Models;
namespace HHECS.DAQServer.Services
{
public class SystemBackgroundService : BackgroundService
{
private readonly IFreeSql _freeSql;
private readonly DataCacheService _dataCacheService;
private readonly ILogger<SystemBackgroundService> _logger;
private readonly int _limit = 1000;
public SystemBackgroundService(IFreeSql freeSql, DataCacheService dataCacheService, ILogger<SystemBackgroundService> logger)
{
_freeSql = freeSql;
_dataCacheService = dataCacheService;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var equipmentDataRecordTemps = new List<EquipmentDataRecord>();
var index = 0;
while (!stoppingToken.IsCancellationRequested)
{
try
{
await Task.Delay(1000, stoppingToken);
if (index >= 100)
{
index = 0;
}
index++;
//每两秒执行一次
if (index % 2 == 0)
{
if (equipmentDataRecordTemps.Count < _limit)
{
for (int i = 0; i < _limit; i++)
{
if (_dataCacheService.EquipmentDataRecordQueue.IsEmpty)
{
break;
}
if (equipmentDataRecordTemps.Count == _limit)
{
break;
}
_dataCacheService.EquipmentDataRecordQueue.TryDequeue(out var data);
equipmentDataRecordTemps.Add(data);
}
}
if (equipmentDataRecordTemps.Count > 0)
{
using var equipmentDataRecordRepository = _freeSql.GetRepository<EquipmentDataRecord>();
equipmentDataRecordRepository.Insert(equipmentDataRecordTemps);
_logger.LogInformation($"[设备记录数据表]成功新增{equipmentDataRecordTemps.Count}条数据!");
equipmentDataRecordTemps.Clear();
}
}
//每5秒执行一次
if (index % 5 == 0)
{
using var clientStatusRepository = _freeSql.GetRepository<ClientStatus>();
var temps = _dataCacheService.ClientStatusQueue.ToArray().Where(x => x.Value >= DateTime.Now.AddMinutes(-5));
//待更新数据
var waitUpdateItem = new List<ClientStatus>();
foreach (var temp in temps)
{
var clientStatusItem = clientStatusRepository.Where(x => x.ClientKeys == temp.Key && x.LastSeenDate < temp.Value).First();
if (clientStatusItem != null)
{
clientStatusRepository.Attach(clientStatusItem);
clientStatusItem.LastSeenDate = temp.Value;
waitUpdateItem.Add(clientStatusItem);
}
}
if (waitUpdateItem.Count > 0)
{
const int limit = 1000;
//分批更新
var pages = waitUpdateItem.Count / limit + Convert.ToInt32(waitUpdateItem.Count % limit > 0);
for (int i = 1; i <= pages; i++)
{
var temp2s = waitUpdateItem.Skip((i - 1) * limit).Take(limit).ToList();
clientStatusRepository.Update(temp2s);
}
}
}
}
catch (Exception ex)
{
_logger.LogError($"[{nameof(SystemBackgroundService)}]线程异常,[设备记录数据表]新增数据失败:{ex.Message}");
}
}
}
}
}