refactor: replace periodic tasks loop with background service
This commit is contained in:
parent
54ec469cd9
commit
fb324e7576
4 changed files with 67 additions and 57 deletions
|
@ -37,9 +37,9 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
return value.Value;
|
||||
}
|
||||
|
||||
public async Task DeleteExpiredKeysAsync()
|
||||
public async Task DeleteExpiredKeysAsync(CancellationToken ct)
|
||||
{
|
||||
var count = await db.TemporaryKeys.Where(k => k.Expires < clock.GetCurrentInstant()).ExecuteDeleteAsync();
|
||||
var count = await db.TemporaryKeys.Where(k => k.Expires < clock.GetCurrentInstant()).ExecuteDeleteAsync(ct);
|
||||
if (count != 0) logger.Information("Removed {Count} expired keys from the database", count);
|
||||
}
|
||||
|
||||
|
|
26
Foxnouns.Backend/Services/PeriodicTasksService.cs
Normal file
26
Foxnouns.Backend/Services/PeriodicTasksService.cs
Normal file
|
@ -0,0 +1,26 @@
|
|||
namespace Foxnouns.Backend.Services;
|
||||
|
||||
public class PeriodicTasksService(ILogger logger, IServiceProvider services) : BackgroundService
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<PeriodicTasksService>();
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
while (await timer.WaitForNextTickAsync(ct))
|
||||
{
|
||||
_logger.Debug("Collecting metrics");
|
||||
await RunPeriodicTasksAsync(ct);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunPeriodicTasksAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.Debug("Running periodic tasks");
|
||||
|
||||
await using var scope = services.CreateAsyncScope();
|
||||
|
||||
var keyCacheSvc = scope.ServiceProvider.GetRequiredService<KeyCacheService>();
|
||||
await keyCacheSvc.DeleteExpiredKeysAsync(ct);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue