-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServiceMonitor.cs
62 lines (52 loc) · 2.2 KB
/
ServiceMonitor.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Threading;
using System.Management;
using System.ServiceProcess;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class ServiceMonitor : BackgroundService
{
private readonly ILogger<ServiceMonitor> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
public ServiceMonitor(ILogger<ServiceMonitor> logger, IServiceScopeFactory serviceScopeFactory)
{
_logger = logger;
_serviceScopeFactory = serviceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("ServiceMonitor is starting.");
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _serviceScopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<XjtfDbContext>();
foreach (var service in ServiceController.GetServices())
{
var timestamp = DateTime.Now;
var serviceName = service.ServiceName;
var serviceStatus = service.Status.ToString();
var record = new ServiceObservation
{
Timestamp = timestamp,
ServiceName = serviceName,
ServiceStatus = serviceStatus
};
dbContext.ServiceObservations.Add(record);
}
dbContext.SaveChanges();
_logger.LogInformation("ServiceMonitor added new records.");
var outdatedRecords = dbContext.ServiceObservations.Where(o => o.Timestamp < DateTime.Now.AddDays(-7)).ToList();
dbContext.ServiceObservations.RemoveRange(outdatedRecords);
dbContext.SaveChanges();
_logger.LogInformation($"ServiceMonitor removed {outdatedRecords.Count} outdated records.");
await Task.Delay(5000, stoppingToken);
}
_logger.LogInformation("ServiceMonitor is stopping.");
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("ServiceMonitor is stopping.");
await base.StopAsync(stoppingToken);
}
}