protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { //每5分钟扫描一次 if (_lastScanTime.AddMinutes(5) > DateTime.Now) { await Task.Delay(10000, stoppingToken); } _lastScanTime = DateTime.Now; using (var unitOfWork = _unitOfWorkManager.Begin()) { List<Log> techLogcationLogList = new List<Log>(); SvTech techInfo = new SvTech(); List<SvTech> techList = new List<SvTech>(); Log techLogcationLog = new Log(); Stopwatch watch = new Stopwatch(); watch.Start(); var LoginData = LoginSystemAsync().Result;//获取登录数据 if (LoginData.success == true) { var GpsData = GetTechLocationAsync(LoginData.id, LoginData.mds).Result;//获取定位数据 if (GpsData.success == true) { foreach (var item in GpsData.data) { foreach (var element in item.records) { Newtonsoft.Json.Linq.JArray location = (Newtonsoft.Json.Linq.JArray)element; object[]? locationArr = location.ToObject<object[]>(); techInfo = _technicianRepository.GetAll().Where(s => s.gps_imei == locationArr[11].ToString()).FirstOrDefault(); if (techInfo != null) { techInfo.current_location = locationArr[2].ToString() + "," + locationArr[3].ToString(); techInfo.location_update_time = DateTime.Now; techList.Add(techInfo); techLogcationLog.technician_id = techInfo.Id; techLogcationLog.location = locationArr[2].ToString() + "," + locationArr[3].ToString(); techLogcationLog.update_datetime = DateTime.Now; techLogcationLogList.Add(techLogcationLog); } } } } else { //获取定位失败 } } else { //登录失败 } if(techList.Count>0) { try {
_technicianLocationLogRepository.GetDbContext().BulkInsert(techLogcationLogList); //批量新增 _technicianRepository.GetDbContext().BulkUpdate(techList); //批量修改 watch.Stop(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } unitOfWork.Complete(); _lastScanTime = DateTime.Now; } } }
注意事项:需要在数据库链接字符串后面加上 AllowLoadLocalInfile=true
"ConnectionStrings": { "Default": "server=127.0.0.1;port=3306;user id=root;password=123456;database=test;AllowLoadLocalInfile=true" },
否则会报如下错误
//错误提示 To use MySqlBulkLoader.Local=true, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data”