Skip to content

Commit bb5dcec

Browse files
committed
improve check and set host ShutdownTimeout
1 parent bafd315 commit bb5dcec

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

ShuttingDownHealthCheck.cs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,41 @@
33
using System.Threading.Tasks;
44
using Microsoft.Extensions.Diagnostics.HealthChecks;
55
using Microsoft.Extensions.Hosting;
6+
using Microsoft.Extensions.Logging;
67

78
namespace blog_zero_downtime_with_health_checks
89
{
910
public class ShuttingDownHealthCheck : IHealthCheck
1011
{
12+
private readonly IHostEnvironment _hostEnvironment;
13+
private readonly ILogger<ShuttingDownHealthCheck> _logger;
14+
1115
private HealthStatus _status = HealthStatus.Healthy;
1216

13-
public ShuttingDownHealthCheck(IHostApplicationLifetime appLifetime)
17+
public ShuttingDownHealthCheck(
18+
IHostApplicationLifetime appLifetime,
19+
IHostEnvironment hostEnvironment,
20+
ILogger<ShuttingDownHealthCheck> logger)
1421
{
22+
_hostEnvironment = hostEnvironment;
23+
_logger = logger;
24+
1525
appLifetime.ApplicationStopping.Register(() =>
1626
{
17-
Console.WriteLine("Shutting down");
1827
_status = HealthStatus.Unhealthy;
28+
29+
// We don't need to block on developer machines as there's no load balancers involved there.
30+
bool delayShutdown = _hostEnvironment.IsProduction();
31+
if (delayShutdown)
32+
{
33+
var shutdownDelay = TimeSpan.FromSeconds(25);
34+
_logger.LogInformation("Delaying shutdown for {Seconds} seconds", shutdownDelay.TotalSeconds);
35+
36+
// ASP.NET Core requests are processed on separate threads, so we can just put the main thread on sleep.
37+
Thread.Sleep(shutdownDelay);
38+
39+
_logger.LogInformation("Shutdown delay completed");
40+
}
1941
});
2042
}
2143

Startup.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ public class Startup
1616
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
1717
public void ConfigureServices(IServiceCollection services)
1818
{
19+
services.Configure<HostOptions>(option =>
20+
{
21+
option.ShutdownTimeout = System.TimeSpan.FromSeconds(30);
22+
});
23+
1924
services.AddSingleton<ShuttingDownHealthCheck>();
2025

2126
services.AddHealthChecks()

0 commit comments

Comments
 (0)