Monitor Process(es), Shutdown if over a threshold CPU Usage
I am new to WMI and System.Diagnostics etc. I need to write something (a service?) that monitors several processes for CPU Usage %. When I am in Task Manager, the CPU column is the one that I want (i.e. the percentage).
I need to be able to run this on a remote machine, and have it check the CPU Usage every second or so. When the usage is over 30%, I need for the offending service to be restarted automatically.
I have read through all(read:most) of the Related questions, and I think the PerformanceCounter is probably the one I need to use, but I am unsure as to whether or not I need one of these for each process, and how to locate the process, (it has to be name based, not PID based).
Can anyone please advise. Summary
- I don't want to loop through all processes on the machine (if I can avoid it)
- I need the CPU Usage % of the process
- I need to restart a process if the usage is over 30%.
You might consider looking at the sources for one of my old Free Software projects: The SETI@Home Service. It implemented a Windows service that pauses its client process (the SETI@Home client) if CPU usage got over a certian value. It even added a couple other sexy twists, like pausing any time certian other processes start up (eg: your favorite game), crash restarts, built-in webserver, etc.
The main drawback is going to be that the sources are in Ada, but most people find Ada easier to read that most other languages they aren't familiar with.
IIRC, the basic gist of the code is that there's an area of the Windows registry you can look in that contains system performance information. Basically anything available inside perfmon can be read from the system registry by a program.
I finally solved my own problem by writing a wrapper around PerformanceCounter and Process. I have a class called a ProcessMonitor which has a PerformanceCounter and a Process as properties. I created another class called a ProcessMonitorList which does a little more than contains List. Then my primary Commandline app has a while(true) which queries for all processes with the provided name and spits out at every second, their CPU usage. If the usage exceeds the threshold, the process is killed and optionally an email is sent to a configured email address.