简体   繁体   中英

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 (eg 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 ):

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM