I've created a hosted service that executes a recurring task in .Net-Core. (I'm using shared hosting so I don't have control over iis)
public class SchedulerService : IHostedService
{
private readonly ILogger _logger;
private Timer _timer;
public SchedulerService(ILogger<SchedulerService> logger)
{
this._logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
this._timer = new Timer(ExecuteTask, null, TimeSpan.Zero,
TimeSpan.FromMinutes(30));
return Task.CompletedTask;
}
private void ExecuteTask(object state)
{
}
public Task StopAsync(CancellationToken cancellationToken)
{
this._timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
}
I'd like to ensure that this task is always run. But Hosted Service's are NOT guaranteed to complete due to app-pool recycles etc.
I'm a bit confused on this notion. I'm under the impression now that Hosted services are only run in the background after a request is made and once the app pool is recycled the background task is killed (e.g 90 second limit from the older version of .net)
EDIT
I tested this in my API and it seems to run continuously even hours after the last requests was made. Note: I tested this in IIS Express so that still doesn't guarantee behavior.
If this is the case, and no request are made to my site, can I still be guaranteed that my SchedulerService will run?
Or should I just have my scheduler service send a request every ~75 seconds to myself, to ensure that a new thread will restart the scheduler?
If you run your ASP.NET Core application in IIS (not IIS Express):
If you run the application as a Windows Service, none of this is needed.
Also, for forward compatibility, make your hosted service inherit the BackgroundService
class and register it for dependency injection using AddHostedService
.
AFAIK, using the IIS in-process hosting model in .NET Core 2.2 has no effect on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With