Reputation: 515
I developed a BackgroundService, at the beginning it works Ok. But later at 20 minutes this is cancelled for some reason that I don't know. For this case in particular, the "job" should be infinite and never finish. Please, could you give some idea ? I'll appreciate it
public class CheckItemsService : BackgroundService
{
private IConfiguration Configuration { get; }
public CheckItemsService(IConfiguration configuration)
{
Configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.Register(() => Log.Information("Job is stopping"));
while (!stoppingToken.IsCancellationRequested)
{
await UpdateItems();
await Task.Delay(1000 * 60, stoppingToken);
}
}
private async Task UpdateItems()
{
var optionsBuilder = new DbContextOptionsBuilder<WalletContext>();
optionsBuilder.UseSqlServer(Configuration.GetSection("ConnectionStrings:Default").Value);
DbContext _context = new DbContext(optionsBuilder.Options);
var items = await _context.EntityX.ToListAsync();
foreach (var item in items)
{
item.ModificationDate = DateTime.Now;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException dbEx)
{
Log.Information(dbEx.Message);
}
}
}
Upvotes: 4
Views: 3324
Reputation: 515
@Scott Chamberlain Thanks man, in base on your comment you gave me the idea of searching why the host was shutting down, so I figured out that IIS has a default configuration for "inactivity" in every site for 20 minutes. I changed this and it's working perfectly. @Vidmantas Blazevicius Thanks so much man, indeed this was the reason of my problem. Appreciate it for your help.
Link where I find the solution of the configuration on IIS → How to prevent IIS from shutting down Web Site when not in use?
Upvotes: 1