From 2b47d8e20d7df1f49295fe26b2544490a09a81c4 Mon Sep 17 00:00:00 2001 From: dmolinari Date: Sun, 7 Sep 2025 23:04:36 -0300 Subject: [PATCH] Fix Worker --- .../LowPriorityDataWorker.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Elecciones-Web/src/Elecciones.Worker/LowPriorityDataWorker.cs b/Elecciones-Web/src/Elecciones.Worker/LowPriorityDataWorker.cs index 33dca54..aaae425 100644 --- a/Elecciones-Web/src/Elecciones.Worker/LowPriorityDataWorker.cs +++ b/Elecciones-Web/src/Elecciones.Worker/LowPriorityDataWorker.cs @@ -762,6 +762,9 @@ public class LowPriorityDataWorker : BackgroundService { _logger.LogInformation("Se encontraron {count} telegramas nuevos en '{partido}' para '{cat}'. Descargando...", nuevosTelegramasIds.Count, partido.Nombre, categoria.Nombre); + int contadorLote = 0; + const int tamanoLote = 100; // Guardaremos de 100 en 100 + foreach (var mesaId in nuevosTelegramasIds) { if (stoppingToken.IsCancellationRequested) return; @@ -769,12 +772,9 @@ public class LowPriorityDataWorker : BackgroundService var telegramaFile = await _apiService.GetTelegramaFileAsync(authToken, mesaId); if (telegramaFile != null) { - // 1. Buscamos el AmbitoGeografico específico de la MESA que estamos procesando. - var ambitoMesa = await innerDbContext.AmbitosGeograficos - .AsNoTracking() + var ambitoMesa = await innerDbContext.AmbitosGeograficos.AsNoTracking() .FirstOrDefaultAsync(a => a.MesaId == mesaId, stoppingToken); - // 2. Solo guardamos el telegrama si encontramos su ámbito de mesa correspondiente. if (ambitoMesa != null) { var nuevoTelegrama = new Telegrama @@ -787,15 +787,30 @@ public class LowPriorityDataWorker : BackgroundService FechaTotalizacion = DateTime.Parse(telegramaFile.FechaTotalizacion).ToUniversalTime() }; await innerDbContext.Telegramas.AddAsync(nuevoTelegrama, stoppingToken); + contadorLote++; // Incrementamos el contador } else { _logger.LogWarning("No se encontró un ámbito geográfico para la mesa con MesaId {MesaId}. El telegrama no será guardado.", mesaId); } } - await Task.Delay(250, stoppingToken); + await Task.Delay(250, stoppingToken); // Mantenemos el delay para no saturar la API + + // Si hemos alcanzado el tamaño del lote, guardamos y reseteamos. + if (contadorLote >= tamanoLote) + { + await innerDbContext.SaveChangesAsync(stoppingToken); + _logger.LogInformation("Guardado un lote de {count} telegramas.", contadorLote); + contadorLote = 0; // Reseteamos el contador para el siguiente lote + } + } + + // Guardamos cualquier registro restante que no haya completado un lote completo. + if (contadorLote > 0) + { + await innerDbContext.SaveChangesAsync(stoppingToken); + _logger.LogInformation("Guardado el último lote de {count} telegramas.", contadorLote); } - await innerDbContext.SaveChangesAsync(stoppingToken); } } await Task.Delay(100, stoppingToken);