Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement