Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

Batch file to restart a specific service based on the CPU of a process

I'm hoping you can help me with this, I've tried researching for hours but can't seem to get anywhere with it.

I have a process which randomly starts to consume 50+ CPU a few times a day, I'm trying to create a batch file which will run in the background and restart the service if the CPU usage of the process gets above 50 (fixes the issue).

I found something very close on this forum, a guy named "Elektro Hacker" answered, but his answer is the overall CPU usage, not just the usage of a specific process. Here is the batch file he suggested:

@Echo OFF

SET    "SERVICE=Themes"
SET /A "MAXUSAGE=95"
SET /A "INTERVAL=5"

:LOOP 
For /F %%P in ('wmic cpu get loadpercentage ^| FINDSTR "[0-9]"') do (
    IF %%P GTR %MAXUSAGE% (
        Echo [%TIME:~0,8%] CPU Usage: %%P%% Reached the limit: %MAXUSAGE%%%
        Echo Restarting %SERVICE% ...
         SC STOP  "%SERVICE%" 1>NUL
        SC START "%SERVICE%" 1>NUL
        Echo Service restarted.
    ) ELSE (
         Echo [%TIME:~0,8%] CPU Usage: %%P%%
    )
)
Ping -n %INTERVAL% Localhost >NUL
GOTO :LOOP

He also put: "For more precission maybe you want to check the current CPU percentage of the executable associated to the service using:

wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessor
Time

This is the part I can't get past, I keep getting errors, and every time I try to fix it by changing it slightly, I get different errors!

Can anybody change this code slightly, to get it to get the CPU of say "MyProcess" The process and service names are different, I'm not sure if this would make a difference but thought it was worth mentioning.

My coding knowledge is minimal at best, so any help or advice you could give me is greatly appreciated, this is driving my crazy!

Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Powesshell can do better

get-process wmiprvse | select processname,cpu,id | ? {$_.cpu -gt 90 -and $_.id} | foreach { restart-service winmgmt }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...