2026-05-22 14:29:22 +08:00
|
|
|
using FileShare_Services.Services.FileLibrary;
|
2026-05-21 16:45:56 +08:00
|
|
|
|
2026-05-22 14:29:22 +08:00
|
|
|
namespace FileShare_API.Services
|
2026-05-21 16:45:56 +08:00
|
|
|
{
|
|
|
|
|
public sealed class FileLibraryScanHostedService(IServiceScopeFactory scopeFactory, ILogger<FileLibraryScanHostedService> logger)
|
|
|
|
|
: BackgroundService
|
|
|
|
|
{
|
|
|
|
|
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<IFileLibraryService>();
|
|
|
|
|
await scanner.ScanDueRootsAsync(cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning(ex, "文件库定时扫描失败。");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|