-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathPingWebsiteBackgroundService.cs
46 lines (43 loc) · 1.84 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
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using HappyCode.NetCoreBoilerplate.Core.Settings;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HappyCode.NetCoreBoilerplate.Api.BackgroundServices
{
public class PingWebsiteBackgroundService : BackgroundService
{
private readonly HttpClient _client;
private readonly ILogger<PingWebsiteBackgroundService> _logger;
private readonly IOptions<PingWebsiteSettings> _configuration;
public PingWebsiteBackgroundService(
IHttpClientFactory httpClientFactory,
ILogger<PingWebsiteBackgroundService> logger,
IOptions<PingWebsiteSettings> configuration)
{
_client = httpClientFactory.CreateClient(nameof(PingWebsiteBackgroundService));
_logger = logger;
_configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
_logger.LogInformation($"{nameof(PingWebsiteBackgroundService)} running at '{DateTime.Now}', pinging '{_configuration.Value.Url}'");
try
{
using var response = await _client.GetAsync(_configuration.Value.Url, cancellationToken);
_logger.LogInformation($"Is '{_configuration.Value.Url.Authority}' responding: {response.IsSuccessStatusCode}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error during ping");
}
await Task.Delay(TimeSpan.FromMinutes(_configuration.Value.TimeIntervalInMinutes), cancellationToken);
}
}
}
}