Skip to content

Commit

Permalink
improve check and set host ShutdownTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
cwe1ss committed Oct 22, 2020
1 parent bafd315 commit bb5dcec
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
26 changes: 24 additions & 2 deletions ShuttingDownHealthCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
});
}

Expand Down
5 changes: 5 additions & 0 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit bb5dcec

Please sign in to comment.