Files
PaperlessAI/Jobs/CheckDocumentsToProcessJob.cs
2026-10-12 01:14:13 +02:00

42 lines
1.5 KiB
C#

using Microsoft.EntityFrameworkCore;
using PaperlessAI.Context;
using PaperlessAI.Models;
using PaperlessAI.Services;
namespace PaperlessAI.Jobs;
public class CheckDocumentsToProcessJob(ILogger<CheckDocumentsToProcessJob> logger, IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using var scope = scopeFactory.CreateAsyncScope();
var config = scope.ServiceProvider.GetRequiredService<Configuration>();
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(config.CheckDocumentsToProcessJobPeriodSeconds));
do
{
await DoWork(stoppingToken);
}
while(await timer.WaitForNextTickAsync(stoppingToken));
}
private async Task DoWork(CancellationToken stoppingToken)
{
logger.LogInformation("Working");
await using var scope = scopeFactory.CreateAsyncScope();
var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();
var documentProcessingService = scope.ServiceProvider.GetRequiredService<DocumentProcessingService>();
var docsToProcess = await context
.PaperlessDocuments
.Where(x => x.DocumentState == Enums.EDocumentState.Created)
.OrderBy(x => x.CreatedAt)
.ToListAsync();
await documentProcessingService.Enqueue(docsToProcess);
await documentProcessingService.Process();
}
}