39 lines
1.3 KiB
C#
39 lines
1.3 KiB
C#
|
|
using Avalonia_Services.Services.FileLibrary;
|
||
|
|
|
||
|
|
namespace Avalonia_API.Services
|
||
|
|
{
|
||
|
|
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, "文件库定时扫描失败。");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|