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