Home > Back-end >  How to an API periodically to receive service health status in Asp.net Core
How to an API periodically to receive service health status in Asp.net Core

Time:11-08

I have a scenario where I have to call API periodically to receive health status.

what if I use a while use?

 while (true)
  {
// API call
   var health = _client.GetHealth(1).Result;
   if (health)
     {
       some other work

     }
   Thread.Sleep(2000);
  }

CodePudding user response:

This is already available through the Health Checks middleware. The health checks service will check the registered probes periodically to see if everything is OK. The health status can be logged or exposed through an API endpoint.

There are several probes available. The open source AspNetCore.Diagnostics.HealthChecks library offers probes from everything from remote APIs to various database products, cloud services and more. It also offers a Health check dashboard that displays detailed health check history.

Using Health Checks is easy, as it's already included in the web app templates.

Registering it requires adding the following to Startup.cs :

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks();
}

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/health");
    });
}

MapHealthChecks exposes a basic status at /health endpoint. To check a remote API you can add the AspNetCore.HealthChecks.Uris package and use one of the AddUrlGroup overloads:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
            .AddUrlGroup(new Uri("http://httpbin.org/status/200"));
}

CodePudding user response:

You can use async programming,

public async Task HealthCheckAsync()
{
 while (true)
  {
// API call
   var health = await _client.GetHealth(1);
   if (health)
     {
       some other work

     }
    await Task.Delay(2000);
  }
}

This works the same way except that it is not blocking the main thread while it waits for the response from server or while it is waiting for next cycle.

  • Related