How to periodically run a script/command when a specific application is being used? 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?
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&gt;3') &amp;&amp; $(lsappinfo visibleProcessList|cut -d\" -f2) = iTerm ]]&amp;&amp;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'