您基本上是正确的,但看起来您在验证这些部分是否正常工作之前试图跳到前面。如果您将处理程序和变量命名为它们正在尝试执行的操作,它也可能会有所帮助。例如,在这种情况下,您的处理程序似乎正在监视一个应用程序,然后在该应用程序达到低 CPU 使用率时退出该应用程序。
请注意,我已在示例中将进程名称更改为 TaskPaper,因为我可以使用它。
quitOnLowCPU("TaskPaper")
on quitOnLowCPU(processToMonitor)
set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print $1}'"
display dialog processCPU
end quitOnLowCPU
此时,我们知道两件事:shell 脚本正在返回我们想要的数字,并且它正在将它作为字符串返回。
为了可靠地比较数字,我们需要将它们转换为数值。
quitOnLowCPU("TaskPaper")
on quitOnLowCPU(processToMonitor)
set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print $1}'"
--convert the shell script response string to a number
set processCPU to processCPU as number
--compare to the threshold of quitting
if processCPU is less than 2.0 then
tell application processToMonitor to quit
end if
end quitOnLowCPU
这可行,但它也会尝试退出 processToMonitor,即使 processToMonitor 没有运行。
quitOnLowCPU("TaskPaper")
on quitOnLowCPU(processToMonitor)
set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print $1}'"
if processCPU is "" then
--the process is gone. We're done
return
end if
--convert the shell script response string to a number
set processCPU to processCPU as number
--compare to the threshold of quitting
if processCPU is less than 2.0 then
tell application processToMonitor to quit
end if
end quitOnLowCPU
现在我们准备在处理程序周围添加repeat:
quitOnLowCPU("TaskPaper")
on quitOnLowCPU(processToMonitor)
repeat
set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print $1}'"
if processCPU is "" then
--the process is gone. We're done
return
end if
--convert the shell script response string to a number
set processCPU to processCPU as number
--compare to the threshold of quitting
if processCPU is less than 2.0 then
tell application processToMonitor to quit
end if
delay 1
end repeat
end quitOnLowCPU
我在每次重复时都添加了delay,因为无休止地重复脚本本身往往会占用 CPU。