Extending the shutdown timeout for BackgroundService

I have a class that derives from BackgroundService and is added as a hosted service in my Startup.cs. In the StopAsync() method I'm doing some pretty long tasks. Some of them are not able to finish because of the ShutdownTimeout option in the Host.cs (link to source) class.
My solution to fix it was to set ShutdownTimeout with IWebHostBuilder.UseShutdownTimeout(), but it doesn't have an impact on the background service.

    private static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseShutdownTimeout(TimeSpan.FromSeconds(60));
                webBuilder.UseStartup<Startup>();
            })
            .UseWindowsService();
    }

Is there a way to set UseShutdownTimeout for the BackgroundService?


Solution 1:

Yes there is

.ConfigureServices((hostContext, services) =>
    {
        services.Configure<HostOptions>(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
    }

I think it is found in the Microsoft.Extensions.DependencyInjection package. From the code you are posting it looks like you are using a webhost which is different to Windows Service or console application.