track/src/SJZY.Track.Application/Services/TimerTaskss/TrackPushTask.cs
2024-10-21 09:12:04 +08:00

94 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
/// <summary>
/// 轨迹推送定时任务
/// </summary>
[ApiExplorerSettings(GroupName = "定时任务")]
public class TrackPushTask : ApplicationService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public TrackPushTask(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <summary>
/// 定时任务推送预警(》12小时没有推送的)
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("/TimerTask/PushWarn")]
public async Task<string> PushWarnForTaskAsync()
{
using var serviceScope = _serviceScopeFactory.CreateScope();
var configs = serviceScope.ServiceProvider.GetRequiredService<IOptionsSnapshot<Track2InterfaceRelayOptions>>()
.Value;
if (configs == null || configs.Keys.Count == 0)
{
throw new BusinessException("未配置子系统");
}
var orderRepository = serviceScope.ServiceProvider.GetRequiredService<IOrderRepository>();
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<IOrderRepository>();
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}个订单");
}
}