I need to do some cleanups in my DB once every day. I'm using a BackgroundService:
public class DbCleanerService : BackgroundService
{
public DbCleanerService(IServiceProvider services)
{
Services = services;
}
public IServiceProvider Services { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// get a db context and do the cleanup
await Task.Delay(TimeSpan.FromDays(1), stoppingToken);
}
}
}
Is there any gotchas that I'm not aware of? Will the long delay cause any problem? For example I've read on many places that this is not safe for IIS hosted websites because IIS might shutdown its unused websites. (I'm not using IIS though)
I'm using ASP.NET Core 6 with Kestrel on Ubuntu Server 18.04.
CodePudding user response:
To answer your actual question. Task.Delay can be used to delay up to int.MaxValue. So yes, your code is OK.
Now as you've pointed out, IIS can wind down websites if you aren't careful, but also during redeployment scenarios, your application will restart and you don't have any way (in your existing code), to track where you are up to. In those scenarios, using something like Hangfire would be better.
However, assuming your DB Cleaner service is fine to be run multiple times per day (e.g. It just cleans up old records and is not required to be run once and only once per day), then you might not even care.
CodePudding user response:
Install FluentScheduler
for the new Asp.Net 6.0 without Startup.cs after var app = builder.Build(); add this to your Program.cs
JobManager.Initialize();
JobManager.AddJob(RunMyJob, s => s.ToRunNow().AndEvery(1).Days());
void RunMyJob()
{
// Do What You Want
var dbContext = app.Services.GetRequiredService<ApplicationDbContext>(); // Injecting Services
}
this will run the "RunMyJob" every day
if you are using startup.cs add this to your startup Configure section
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext applicationDbContext) // Injecting ApplicationDbContext Service
{
JobManager.Initialize();
JobManager.AddJob(RunMyJob, s => s.ToRunNow().AndEvery(1).Days());
void RunMyJob()
{
// Do What You Want
}
...
}
For more information visit FluentScheduler Docs
CodePudding user response:
I would recommend you Hangfire. Hangfire has a Recurring jobs feature.
Recurring jobs fire many times on the specified CRON schedule.
