In an application there is a table for one-time-passwords (OTP) which will be sent to users via SMS. These OTPs are needed for a maximum of two hours in order to detect abusing behaviours.
A simple DB cleaner will delete these rows (DeleteAsync is from this library):
public class DbCleaner : BackgroundService
{
private readonly IServiceProvider serviceProvider;
private readonly ILogService logService;
public DbCleaner(
IServiceProvider serviceProvider,
ILogService logService)
{
this.serviceProvider = serviceProvider;
this.logService = logService;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<IdentityDbContext>();
var otpDeleted = await dbContext.OTP
.IgnoreQueryFilters()
.Where(x => x.CreationTime.AddHours(2) >= DateTimeOffset.UtcNow)
.DeleteAsync();
await LogOperationAsync(otpDeleted);
try
{
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
catch (TaskCanceledException)
{
// application is shutting down
// ignore this
}
}
}
private Task LogOperationAsync(int otpCount)
{
// ...
}
}
On every publish, the timer will be reset which is fine for this project.