using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using SJZY.Expand.ABP.Core; using SJZY.Expand.ABP.Core.Logger; using SJZY.Track.Application.Track2InterfaceRelay; using SJZY.Track.Domain.Aggregates.OrderAggregate; namespace SJZY.Track.Application.Services.TimerTaskss; /// /// 轨迹推送定时任务 /// [ApiExplorerSettings(GroupName = "定时任务")] public class TrackPushTask : ApplicationService { private readonly IServiceScopeFactory _serviceScopeFactory; public TrackPushTask(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } /// /// 定时任务推送预警(》12小时没有推送的) /// /// [AllowAnonymous] [HttpPost("/TimerTask/PushWarn")] public async Task PushWarnForTaskAsync() { using var serviceScope = _serviceScopeFactory.CreateScope(); var configs = serviceScope.ServiceProvider.GetRequiredService>() .Value; if (configs == null || configs.Keys.Count == 0) { throw new BusinessException("未配置子系统"); } var orderRepository = serviceScope.ServiceProvider.GetRequiredService(); var subSystemIds = await orderRepository.GetSubSystemListByCodesAsync(configs.Keys.ToList()); foreach (var item in subSystemIds) { await PushWarningBySubSystemAsync(serviceScope, item.id); } await Task.Delay(1000); // life-time possible dispose return "预警中"; } private async Task PushWarningBySubSystemAsync(IServiceScope serviceScope, int subSystemId) { var redisKey = $"{GlobalConst.TrackPushWaringKeyPrefix}:{subSystemId}"; if (await RedisHelper.Client.ExistsAsync(redisKey)) { return; } await RedisHelper.Client.SetAsync(redisKey, 1, TimeSpan.FromHours(1)); _ = Task.Run(async () => { try { var orderRepository = serviceScope.ServiceProvider.GetRequiredService(); await DoPushWarningAsync(orderRepository, subSystemId); } catch (Exception e) { await RedisHelper.Client.DelAsync(redisKey); LogHelper.Error(e.ToString()); } }); } private async Task DoPushWarningAsync(IOrderRepository orderRepository, int subSystemId) { int total = 0, pageSize = 1000, waitTime = 1000; int rows; var pageindex = 0; do { rows = await orderRepository.PushWarnOrdersAsync(subSystemId, pageSize, pageindex); pageindex++; total += rows; await Task.Delay(waitTime); } while (rows == pageSize); LogHelper.Info($"本次预警扫描了:{total}个订单"); } }