2024-04-03 12:05:44 -07:00

41 lines
1.5 KiB
C#

using FabApprovalWorkerService.Models;
namespace FabApprovalWorkerService.Services;
public class WindowsService : BackgroundService {
private readonly ILogger<WindowsService> _logger;
private readonly IMonInWorkerClient _monInClient;
public WindowsService(ILogger<WindowsService> logger,
IServiceProvider serviceProvider) {
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
using (IServiceScope scope = serviceProvider.CreateScope()) {
_monInClient = scope.ServiceProvider.GetService<IMonInWorkerClient>() ??
throw new ArgumentNullException("IMonInWorkerClient not injected");
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
_logger.LogInformation("Starting Windows service");
try {
while (!stoppingToken.IsCancellationRequested) {
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
_monInClient.PostStatus("WindowsService", StatusValue.Ok);
}
} catch (OperationCanceledException) {
_logger.LogError("The Windows service has been stopped");
_monInClient.PostStatus("WindowsService", StatusValue.Critical);
} catch (Exception ex) {
_logger.LogError($"An exception occurred when running Windows Service. Exception: {ex.Message}");
_monInClient.PostStatus("WindowsService", StatusValue.Critical);
Environment.Exit(1);
}
}
}