MilliSim/backend/MilliSim.Api/Services/UploadCleanupJob.cs

57 lines
1.7 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 MilliSim.Services.Infrastructure;
namespace MilliSim.Services;
/// <summary>
/// 后台定时任务:垃圾资源清理。
/// 每 6 小时扫描 PendingUploads 表,清理 24 小时前上传但未被消费(未保存到实体)的孤立文件。
/// 应对浏览器关闭、刷新等极端情况下前端无法触发清理的场景。
/// </summary>
public class UploadCleanupJob : IHostedService, IDisposable
{
private readonly IServiceProvider _serviceProvider;
private Timer? _timer;
// 检查间隔6 小时
private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(6);
// 过期时间24 小时未消费则清理
private const int ExpireHours = 24;
public UploadCleanupJob(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Task StartAsync(CancellationToken cancellationToken)
{
// 启动后 5 分钟执行第一次(避免启动时并发),之后每 6 小时一次
_timer = new Timer(DoWork, null, TimeSpan.FromMinutes(5), CheckInterval);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
private async void DoWork(object? state)
{
try
{
using var scope = _serviceProvider.CreateScope();
var uploadTracking = scope.ServiceProvider.GetRequiredService<IUploadTrackingService>();
await uploadTracking.CleanupExpiredAsync(ExpireHours);
}
catch
{
// 后台任务异常不应影响应用运行
}
}
}