Files
jinko.yikatong/Src/Dlhis.ScheduledTask/Jobs/ArchiveDeviceUploadLogJob.cs

72 lines
2.6 KiB
C#
Raw Permalink 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 Dlhis.Entity.Device.Entities;
using Dlhis.ScheduledTask.Attributes;
namespace Dlhis.ScheduledTask.Jobs;
/// <summary>
/// 归档设备通行记录的定时任务作业
/// </summary>
[RecurringJob(nameof(ArchiveDeviceUploadLogJob), "0 0 3 * * ? ", Name = "归档设备通行记录")]
public class ArchiveDeviceUploadLogJob : BaseJob
{
/// <summary>
/// 构造函数,注入服务提供者。
/// </summary>
/// <param name="serviceProvider">服务提供者</param>
public ArchiveDeviceUploadLogJob(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
/// 执行归档任务的主方法。
/// 查询60天前的数据,分批归档到指定表,并从主表删除,操作包含事务控制。
/// </summary>
/// <param name="serviceProvider">服务提供者</param>
/// <returns>异步任务</returns>
protected override async Task RunAsync(IServiceProvider serviceProvider)
{
// 设置60天前的数据需要归档
var before60Days = DateTime.Today.AddDays(-60).AddSeconds(1);
// 每次查询500条数据
const int limit = 500;
// 归档表
const string tableName = "deviceuploadlog_20250107";
/*
分批查询并归档60天前的设备通行记录数据。
每次最多处理500条数据,先从主表删除,再插入到归档表,整个过程在事务中完成。
若查询到的数据量等于分页上限,则继续处理下一批,直到数据处理完毕。
*/
List<DeviceUploadLogEntity> data;
do
{
data = await DbContext.Queryable<DeviceUploadLogEntity>()
.Where(x => x.RaiseDateTime < before60Days)
.OrderBy(x => x.Id)
.ToPageListAsync(1, limit);
// ReSharper disable once InvertIf
if (data.Any())
{
await DbContext.Client.Ado.BeginTranAsync();
try
{
await DbContext.DeleteReallyAsync(data);
foreach (var item in data)
{
item.Id = 0;
}
await DbContext.Client.Insertable(data).AS(tableName).ExecuteCommandAsync();
await DbContext.Client.Ado.CommitTranAsync();
}
catch //忽略异常,确保99.99%情况下异常不会触发!!!
{
await DbContext.Client.Ado.RollbackTranAsync();
}
await Task.Delay(200);
}
} while (data.Count == limit);
}
}