You’ve got it basically correct, but it looks like you tried to jump ahead before verifying that the pieces work correctly. It may also help if you name the handlers and variables what they are trying to do. For example, in this case, it seems like your handler is monitoring an app, and then quitting that app once it hits a low CPU usage.
Note that I’ve changed the process name to TaskPaper
in the examples, because I have that available.
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
At this point, we know two things: that the shell script is returning the number we want, and that it’s returning it as a string.
To reliably compare numbers, we need to convert them to numeric values.
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
This works, but it also tries to quit processToMonitor
even if processToMonitor
isn’t running.
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
Now we’re ready to add a repeat
around the handler:
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
I added a delay
on each repeat because endlessly repeating scripts can often become a CPU hog in themselves.