using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Drab.LocalDb; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Drab.Logic.Services; public class OldOrdersCleanupService : BackgroundService { private readonly IServiceProvider _services; private readonly ILogger _logger; private readonly TimeSpan _interval = TimeSpan.FromHours(24); public OldOrdersCleanupService(IServiceProvider services, ILogger logger) { _services = services; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using var scope = _services.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); var threshold = DateTime.Now.AddDays(-45); var oldOrders = dbContext.Orders .Where(o => o.Created < threshold) .ToList(); if (oldOrders.Count != 0) { dbContext.Orders.RemoveRange(oldOrders); await dbContext.SaveChangesAsync(stoppingToken); _logger.LogInformation("Usunięto {OldOrdersCount} starych zamówień.", oldOrders.Count); } else { _logger.LogInformation("Nie znaleziono starych zamówień do usunięcia."); } } catch (Exception ex) { _logger.LogError(ex, "Błąd podczas usuwania starych zamówień."); } await Task.Delay(_interval, stoppingToken); } } }