58 lines
1.9 KiB
C#
58 lines
1.9 KiB
C#
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<OldOrdersCleanupService> _logger;
|
|
private readonly TimeSpan _interval = TimeSpan.FromHours(24);
|
|
|
|
public OldOrdersCleanupService(IServiceProvider services, ILogger<OldOrdersCleanupService> 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<LocalDbContext>();
|
|
|
|
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);
|
|
}
|
|
}
|
|
} |