Created Windows Service
This commit is contained in:
40
FabApprovalWorkerService/Services/WindowsService.cs
Normal file
40
FabApprovalWorkerService/Services/WindowsService.cs
Normal file
@ -0,0 +1,40 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user