Background Service läuft im 60 Sekunden Rythmus. Ergebnis wird noch nciht gespeichert
This commit is contained in:
59
Watcher/Services/NetworkCheck.cs
Normal file
59
Watcher/Services/NetworkCheck.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using System.Composition;
|
||||
using System.Net.NetworkInformation;
|
||||
|
||||
namespace Watcher.Services;
|
||||
public class NetworkCheck : BackgroundService
|
||||
{
|
||||
private readonly ILogger<NetworkCheck> _logger;
|
||||
|
||||
public static String networkCheckResult
|
||||
{
|
||||
get { return networkCheckResult; }
|
||||
set { networkCheckResult = value; }
|
||||
|
||||
}
|
||||
|
||||
public NetworkCheck(ILogger<NetworkCheck> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
|
||||
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
// Hintergrundprozess abwarten
|
||||
await checkConnectionAsync();
|
||||
|
||||
// 5 Sekdunden Offset
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
public Task checkConnectionAsync()
|
||||
{
|
||||
_logger.LogInformation("Networkcheck started.");
|
||||
|
||||
string host = "8.8.8.8";
|
||||
Ping p = new Ping();
|
||||
|
||||
try
|
||||
{
|
||||
PingReply reply = p.Send(host, 3000);
|
||||
if (reply.Status == IPStatus.Success)
|
||||
{
|
||||
_logger.LogInformation("Ping successfull. Watcher is online.");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_logger.LogError("Ping failed. Watcher appears to have no network connection.");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Networkcheck finished.");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user