using Dlhis.Entity.Device.Entities;
using Dlhis.ScheduledTask.Attributes;
namespace Dlhis.ScheduledTask.Jobs;
///
/// 归档设备通行记录的定时任务作业
///
[RecurringJob(nameof(ArchiveDeviceUploadLogJob), "0 0 3 * * ? ", Name = "归档设备通行记录")]
public class ArchiveDeviceUploadLogJob : BaseJob
{
///
/// 构造函数,注入服务提供者。
///
/// 服务提供者
public ArchiveDeviceUploadLogJob(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
///
/// 执行归档任务的主方法。
/// 查询60天前的数据,分批归档到指定表,并从主表删除,操作包含事务控制。
///
/// 服务提供者
/// 异步任务
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 data;
do
{
data = await DbContext.Queryable()
.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);
}
}