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(); } }); } } }