Files
GymLogAI/GymLogAI.Worker/ParsePendingTelegramMessagesJob.cs
T
2026-04-19 13:12:04 +03:00

41 lines
1.5 KiB
C#

using GymLogAI.Application.Handlers;
using GymLogAI.Application.Interfaces;
using Microsoft.Extensions.Options;
namespace GymLogAI.Worker;
public sealed class ParsePendingTelegramMessagesJob(
IServiceProvider serviceProvider,
IOptions<WorkerOptions> options,
ILogger<ParsePendingTelegramMessagesJob> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var scope = serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<ITelegramMessageRepository>();
var handler = scope.ServiceProvider.GetRequiredService<ParseTelegramMessageHandler>();
var pendingMessages = await repository.GetPendingAsync(options.Value.BatchSize, stoppingToken);
foreach (var pendingMessage in pendingMessages)
{
await handler.HandleAsync(pendingMessage.Id, stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to process pending telegram messages.");
}
await Task.Delay(TimeSpan.FromSeconds(options.Value.PollingIntervalSeconds), stoppingToken);
}
}
}