SystemBackgroudService.cs 4.44 KB
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}");
                }
            }
        }
    }
}