Skip to content

Instantly share code, notes, and snippets.

@CarlosLanderas
Created September 29, 2019 19:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CarlosLanderas/d62e3b21d27c9cece31fe147bed467c9 to your computer and use it in GitHub Desktop.
Save CarlosLanderas/d62e3b21d27c9cece31fe147bed467c9 to your computer and use it in GitHub Desktop.
WorkerService + HealthCheck
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace WorkerService1
{
public class Program
{
public static void Main(string[] args)
{
var witness = new WorkerWitness();
WebHost.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services
.AddSingleton(sp => witness)
.AddHealthChecks()
.AddCheck<WorkerHealthCheck>("worker1");
})
.Configure(app =>
{
app
.UseRouting()
.UseEndpoints(config =>
{
config.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => true
});
});
})
.Build()
.StartAsync();
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services
.AddSingleton(sp => witness)
.AddHostedService<Worker>();
})
.Build()
.Run();
}
}
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly WorkerWitness _witness;
public Worker(ILogger<Worker> logger, WorkerWitness witness)
{
_logger = logger;
_witness = witness;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
_witness.LastExecution = DateTime.Now;
await Task.Delay(1000, stoppingToken);
}
}
}
internal class WorkerHealthCheck : IHealthCheck
{
private readonly WorkerWitness _witness;
public WorkerHealthCheck(WorkerWitness witness)
{
_witness = witness;
}
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
//Check if service run for the last 2 mins
return DateTime.Now.Subtract(_witness.LastExecution).TotalSeconds < 120 ?
Task.FromResult(HealthCheckResult.Healthy()) :
Task.FromResult(HealthCheckResult.Unhealthy());
}
}
public class WorkerWitness
{
public DateTime LastExecution { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment