Last active
August 23, 2020 18:09
-
-
Save corespider/abcc9d04843b1604c6dc511ec7260c5d to your computer and use it in GitHub Desktop.
Worker Service in .NET Core- Worker Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Worker : BackgroundService | |
{ | |
private readonly ILogger<Worker> _logger; | |
private HttpClient client; | |
public Worker(ILogger<Worker> logger) | |
{ | |
_logger = logger; | |
} | |
public override Task StartAsync(CancellationToken cancellationToken) | |
{ | |
client = new HttpClient(); | |
return base.StartAsync(cancellationToken); | |
} | |
public override Task StopAsync(CancellationToken cancellationToken) | |
{ | |
client.Dispose(); | |
_logger.LogInformation("The service has been stopped..."); | |
return base.StopAsync(cancellationToken); | |
} | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
while (!stoppingToken.IsCancellationRequested) | |
{ | |
var result = await client.GetAsync("https://www.corespider.com"); | |
if (result.IsSuccessStatusCode) | |
{ | |
_logger.LogInformation("CoreSpider is running and the Status code {StatusCode}", result.StatusCode); | |
} | |
else | |
{ | |
_logger.LogError("CoreSpider is is down. Status code {StatusCode}", result.StatusCode); | |
} | |
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); | |
await Task.Delay(10000, stoppingToken); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment