Files
messengerapi.Broker/code/MessengerBroker/Handlers/HousekeepingHandler.cs
2025-07-05 18:02:25 +02:00

42 lines
1.3 KiB
C#

using MessengerBroker.Configuration.Model;
using MessengerBroker.Factories;
using Microsoft.EntityFrameworkCore;
namespace MessengerBroker.Handlers
{
public class HousekeepingHandler
{
private readonly BrokerConfiguration brokerConfiguration;
private readonly BrokerDbContextFactory brokerDbContextFactory;
public HousekeepingHandler(BrokerConfiguration brokerConfiguration)
{
this.brokerConfiguration = brokerConfiguration;
}
public Task BeginHousekeeping(CancellationToken ct = default)
{
if(this.brokerConfiguration.HousekeepingEnabled == false)
{
return Task.CompletedTask;
}
return Task.Run(async () =>
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(1));
using var context = this.brokerDbContextFactory.CreateDbContext();
var oldestAllowedTimestamp = DateTime.UtcNow.AddMinutes(-this.brokerConfiguration.HousekeepingMessageAgeInMinutes);
await context.Messages
.Where(x => x.TimestampUtc < oldestAllowedTimestamp)
.ExecuteDeleteAsync();
}
});
}
}
}