-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessLifetimeManager.cs
More file actions
84 lines (75 loc) · 2.53 KB
/
ProcessLifetimeManager.cs
File metadata and controls
84 lines (75 loc) · 2.53 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace veeam_task
{
public class ProcessLifetimeManager
{
private readonly ManagerInput mInput;
private readonly ILogger<ProcessLifetimeManager> _logger;
public ProcessLifetimeManager(ManagerInput mInput, ILogger<ProcessLifetimeManager> logger)
{
this.mInput = mInput;
_logger = logger;
}
public void manageLifetime()
{
// No need for exception checking. Previous checks for strict posive and overflow.
Timer monitorTimer = new Timer(mInput.MonitorFreq);
monitorTimer.Elapsed += checkProcessLifetime;
monitorTimer.AutoReset = true;
monitorTimer.Enabled = true;
Program.PressQToExit(0);
}
private void checkProcessLifetime(Object source, ElapsedEventArgs e)
{
Process[] managedProcesses = Process.GetProcessesByName(mInput.ProcessName);
foreach (var process in managedProcesses)
{
TimeSpan lifetime;
try
{
lifetime = DateTime.Now - process.StartTime;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
continue;
}
if (lifetime.TotalMinutes > mInput.MaxLifetime)
{
try
{
int pid = process.Id;
process.Kill();
_logger.LogInformation("Process {0} with id {1} has been killed.", mInput.ProcessName, pid);
}
catch (Exception ex)
{
_logger.LogWarning(ex.Message);
}
}
}
}
public bool Equals(ProcessLifetimeManager manager)
{
if (manager is null)
{
return false;
}
if (ReferenceEquals(this, manager))
{
return true;
}
return (mInput.ProcessName == manager.mInput.ProcessName) &&
(mInput.MaxLifetime == manager.mInput.MaxLifetime) &&
(mInput.MonitorFreq == manager.mInput.MonitorFreq);
}
}
}