Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do recurring Hosted Services require keep alive?

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?

like image 494
johnny 5 Avatar asked Dec 13 '18 01:12

johnny 5


1 Answers

If you run your ASP.NET Core application in IIS (not IIS Express):

  • For your hosted service to start automatically, you need to set the Start Mode of the application pool to Always Running. See Rick Strahl for more information.
  • For your hosted service to keep running indefinitely, you need to set the Idle Time-out of the application pool to 0.

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.

like image 171
bzlm Avatar answered Nov 02 '22 03:11

bzlm