MacOS – How to periodically run a script/command when a specific application is being used

applescriptautomationmacos

I would like a certain applescript to run every 10 seconds but only when a specific application is being used (i.e. both being the front application AND the mouse or keyboard being used in the last few seconds).

How can I create such a trigger?

Best Answer

This runs say a if the time since the last HID (pointing device or keyboard) event is over 3 seconds and if the frontmost application is iTerm:

while sleep 10;do [[ $(ioreg -c IOHIDSystem|awk '/HIDIdleTime/{print $NF/1000000000;exit}'|awk '$0>3') && $(lsappinfo visibleProcessList|cut -d\" -f2) = iTerm ]]&&say a;done

Different ways to get the name of the frontmost application:

lsappinfo visibleProcessList|cut -d\" -f2
lsappinfo find ASN=$(lsappinfo front)|cut -d\" -f2
osascript -e 'name of app (path to frontmost application as text)'
osascript -e 'tell app "System Events" to name of process 1 where frontmost is true'