我希望能够自动化处理,每当一个进程使用超过50%的CPU时,它会向我的通知中心发送一条通知。
我正在使用terminal-notifier来发送通知,但是我不确定最佳方法是使用Automator.app还是创建一个自定义的AppleScript,如果使用后者,如何让它始终处于开启状态?
我正在使用terminal-notifier来发送通知,但是我不确定最佳方法是使用Automator.app还是创建一个自定义的AppleScript,如果使用后者,如何让它始终处于开启状态?
Dock 图标 > 显示 CPU 使用情况
- 或者,对于浮动窗口,选择 监视器 > 显示 CPU 使用情况
。您将获得当前 CPU 使用率的每个核心显示 - 单击它将显示完整的活动监视器窗口,在那里您可以按 CPU 使用率进行排序。
#!/usr/bin/env bash
read pct name < <(top -l 2 -n 1 -F -o cpu -stats cpu,command | tail -1)
if (( ${pct%.*} >= 50 )); then
/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier \
-message "Process > 50%: $name ($pct%)"
fi
launchd
在登录时运行:请参见https://dev59.com/qmAh5IYBdhLWcg3wE_7v#22872222
- launchd
*.plist
文件的一般格式在https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html或 man launchd.plist
中描述; StartInterval
是指定每N秒调用的关键。
实现自动化解决方案的逐步说明:
~/watchcpu
(即在您的主文件夹中创建watchcpu
文件),将上述bash脚本粘贴到其中并保存。~/Library/LaunchAgents/WatchCPU.plist
,将以下XML文档粘贴到其中并保存:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>WatchCPU</string>
<key>ProgramArguments</key>
<array>
<string>bash</string>
<string>-c</string>
<string>. ~/watchcpu</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>15</integer>
</dict>
</plist>
launchctl load ~/Library/LaunchAgents/WatchCPU.plist
.plist
文件必须驻留在 ~/Library/LaunchAgents
中才能在登录时自动加载。StartInterval
)选择为15秒;同样,您可以自由更改它,但请注意,选择更频繁的调用并没有多大意义,因为 launchd
(调用启动代理程序的服务)会对执行时间与调用间隔太接近的代理程序进行限制;我不清楚细节,但在手头的解决方案中,10秒的间隔时间会导致 system.log
中频繁出现限制通知(通过 Console.app 检查)。bash
脚本中放了一个循环吗? - mklement0您可以轻松地使用脚本或自动化工作流程来获取CPU使用率。以下是一个脚本,您可以安排定期运行,并在使用率超过50%时通知:
set theDelay to 3 -- number of seconds to sample the CPU
set CPUusage to do shell script "top -F -l " & theDelay & " -n 1 -stats cpu | grep 'CPU usage:' | tail -1 | cut -d. -f1"
set idlePercent to word -2 of CPUusage as number
if idlePercent < 50 then display notification ("CPU usage is at " & (100 - idlePercent) & "%.") with title "CPU Usage"
yes > /dev/null & yes > /dev/null & yes > /dev/null & yes > /dev/null &
来对我的CPU进行了压力测试,但出现了以下错误:_error ""44.22"无法转换为数字类型。"number -1700 from "44.22" to number - thibmaekgrep
作为GREP
调用是有效的,但我建议使用实际可执行文件名中的大小写,即grep
(只是为了养成更具可移植性的习惯)。 - mklement0