mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
39 lines
1.5 KiB
C#
39 lines
1.5 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using SharpbinV3.Server.Data;
|
|
|
|
namespace SharpbinV3.Server.Services
|
|
{
|
|
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
|
|
{
|
|
private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
using var timer = new PeriodicTimer(_period);
|
|
await Cleanup(stoppingToken);
|
|
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
|
|
{
|
|
try
|
|
{
|
|
await Cleanup(stoppingToken);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error occurred during paste cleanup");
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task Cleanup(CancellationToken stoppingToken)
|
|
{
|
|
using var scope = serviceProvider.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
var expiredPastes = db.Pastes.Where(p => p.ExpiresAt != 0 && p.ExpiresAt <= now);
|
|
var deletedCount = await expiredPastes.ExecuteDeleteAsync(stoppingToken);
|
|
if (deletedCount > 0)
|
|
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
|
|
}
|
|
}
|
|
}
|