FileShare/FileShare-API/Services/FileLibraryScanHostedService.cs

53 lines
2.0 KiB
C#
Raw Normal View History

2026-05-22 14:29:22 +08:00
using FileShare_Services.Services.FileLibrary;
2026-05-22 14:29:22 +08:00
namespace FileShare_API.Services
{
/// <summary>
/// 文件库定时扫描后台服务,每分钟执行一次扫描,检查是否有需要扫描的文件库目录。
/// </summary>
public sealed class FileLibraryScanHostedService(IServiceScopeFactory scopeFactory, ILogger<FileLibraryScanHostedService> logger)
: BackgroundService
{
/// <summary>
/// 扫描间隔,固定为 1 分钟。
/// </summary>
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
/// <summary>
/// 启动扫描循环,首次立即执行,之后按 <see cref="Interval"/> 周期重复执行。
/// </summary>
/// <param name="stoppingToken">应用关闭时触发的取消令牌。</param>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ScanAsync(stoppingToken);
using var timer = new PeriodicTimer(Interval);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await ScanAsync(stoppingToken);
}
}
/// <summary>
/// 创建临时作用域并调用 <see cref="IFileLibraryService.ScanDueRootsAsync"/> 执行一次到期扫描。
/// </summary>
/// <param name="cancellationToken">取消令牌。</param>
private async Task ScanAsync(CancellationToken cancellationToken)
{
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var scanner = scope.ServiceProvider.GetRequiredService<IFileLibraryService>();
await scanner.ScanDueRootsAsync(cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
logger.LogWarning(ex, "文件库定时扫描失败。");
}
}
}
}