Skip to content
Permalink
Browse files
improve check and set host ShutdownTimeout
  • Loading branch information
cwe1ss committed Oct 22, 2020
1 parent bafd315 commit bb5dcecc68d20d5179b8d36fa22f468162e928b8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
@@ -3,19 +3,41 @@
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace blog_zero_downtime_with_health_checks
{
public class ShuttingDownHealthCheck : IHealthCheck
{
private readonly IHostEnvironment _hostEnvironment;
private readonly ILogger<ShuttingDownHealthCheck> _logger;

private HealthStatus _status = HealthStatus.Healthy;

public ShuttingDownHealthCheck(IHostApplicationLifetime appLifetime)
public ShuttingDownHealthCheck(
IHostApplicationLifetime appLifetime,
IHostEnvironment hostEnvironment,
ILogger<ShuttingDownHealthCheck> logger)
{
_hostEnvironment = hostEnvironment;
_logger = logger;

appLifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Shutting down");
_status = HealthStatus.Unhealthy;

// We don't need to block on developer machines as there's no load balancers involved there.
bool delayShutdown = _hostEnvironment.IsProduction();
if (delayShutdown)
{
var shutdownDelay = TimeSpan.FromSeconds(25);
_logger.LogInformation("Delaying shutdown for {Seconds} seconds", shutdownDelay.TotalSeconds);

// ASP.NET Core requests are processed on separate threads, so we can just put the main thread on sleep.
Thread.Sleep(shutdownDelay);

_logger.LogInformation("Shutdown delay completed");
}
});
}

@@ -16,6 +16,11 @@ public class Startup
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.Configure<HostOptions>(option =>
{
option.ShutdownTimeout = System.TimeSpan.FromSeconds(30);
});

services.AddSingleton<ShuttingDownHealthCheck>();

services.AddHealthChecks()

0 comments on commit bb5dcec

Please sign in to comment.