假设我有一个应用程序,它每月有 1000 万用户,我需要每 2 天从数据库中清理会话数据,我应该使用 .net 核心中的内置后台服务,还是使用 hangfire 更好、性能更好?最好的方法是什么?
我把它做成这样的BackgroundService
public class SessionCleanupService : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public SessionCleanupService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Wait until the next 15 day
var now = DateTime.Now;
var nextDay = now.AddDays(15).Date;
var delay = nextDay - now;
await Task.Delay(delay, stoppingToken);
// Delete expired data
using (var scope = _serviceScopeFactory.CreateScope())
{
var _context = scope.ServiceProvider.GetRequiredService<VincheckDbContext>();
var expiredData = await _context.Sessions
.Where(x => EF.Functions.DateDiffDay(x.UpdatedDate, now) > 2)
.ToListAsync();
_context.Sessions.RemoveRange(expiredData);
await _context.SaveChangesAsync();
}
}
}
}
如果你需要一个简单轻量级的解决方案,你可以使用.NET Core 中内置的后台服务。这将允许您定期运行任务,而无需安装任何额外的包或依赖项。
如果你需要更高级的后台任务调度和控制,那么Hangfire值得考虑。 Hangfire 提供延迟作业、重复作业和自动重试等功能。它还提供了一个用于监视和管理后台作业的仪表板。但是,使用第三方库可能会增加应用程序的复杂性和额外的依赖性。
你真的需要 Hangfire 提供的所有附加功能吗?您的场景听起来很简单,也许可以卡住开箱即用的解决方案?