-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
PingWebsiteBackgroundService.cs
58 lines (52 loc) · 2.35 KB
/
PingWebsiteBackgroundService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Net;
using System.Net.Http;
using HappyCode.NetCoreBoilerplate.Core.Settings;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HappyCode.NetCoreBoilerplate.Api.BackgroundServices
{
public interface IPingService
{
public HttpStatusCode WebsiteStatusCode { get; }
}
public class PingWebsiteBackgroundService : BackgroundService, IPingService
{
private readonly PeriodicTimer _timer;
private readonly HttpClient _client;
private readonly ILogger<PingWebsiteBackgroundService> _logger;
private readonly IOptions<PingWebsiteSettings> _configuration;
public HttpStatusCode WebsiteStatusCode { get; private set; }
public PingWebsiteBackgroundService(
IHttpClientFactory httpClientFactory,
ILogger<PingWebsiteBackgroundService> logger,
IOptions<PingWebsiteSettings> configuration)
{
_client = httpClientFactory.CreateClient(nameof(PingWebsiteBackgroundService));
_logger = logger;
_configuration = configuration;
_timer = new PeriodicTimer(TimeSpan.FromMinutes(_configuration.Value.TimeIntervalInMinutes));
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
_logger.LogInformation("{BackgroundService} running at '{Date}', pinging '{URL}'",
nameof(PingWebsiteBackgroundService), DateTime.Now, _configuration.Value.Url);
try
{
using var response = await _client.GetAsync(_configuration.Value.Url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
WebsiteStatusCode = response.StatusCode;
_logger.LogInformation("Is '{Host}' responding: {Status}",
_configuration.Value.Url.Authority, response.IsSuccessStatusCode);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error during ping");
}
await _timer.WaitForNextTickAsync(cancellationToken);
}
_timer.Dispose();
}
}
}