QUIT applications upon reaching the specified IDLE TIME threshold

The script should be used as stay-open application.


-- This script is designed by me to automatically unload the CPU 
-- upon reaching the specified IDLE TIME threshold.
-- It automatically terminates the applications I use frecuencly
-- (those that are persistently in my Dock):

use framework "Foundation"
use framework "AppKit"
use scripting additions
property triggerTime : 5 * minutes
property appsToQuit : {}

set appsToQuit to my dockPersistentAppNames()


on idle
	set idleTime to (do shell script "/usr/sbin/ioreg -c IOHIDSystem | /usr/bin/awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'") as integer
	if idleTime > triggerTime then
		set runningApps to my getRunningApplications()
		repeat with myApp in runningApps
			set myApp to contents of myApp
			if myApp is in appsToQuit then
				try
					tell application myApp to quit saving yes
				end try
			end if
		end repeat
	end if
	return 10
end idle


on getRunningApplications()
	set theWorkspace to current application's NSWorkspace's sharedWorkspace()
	set appList to theWorkspace's runningApplications()
	set appNames to current application's NSMutableArray's array()
	repeat with anApp in appList
		try
			set {theResult, theError} to ((anApp's bundleURL())'s getResourceValue:(reference) forKey:(current application's NSURLApplicationIsScriptableKey) |error|:(missing value))
			if theResult as boolean then (appNames's addObject:(anApp's localizedName()))
		end try
	end repeat
	return appNames as list
end getRunningApplications


on dockPersistentAppNames()
	set dockDefaults to current application's class "NSUserDefaults"'s alloc()'s initWithSuiteName:"com.apple.dock"
	set apps to (dockDefaults's objectForKey:"persistent-apps") as list
	set persistentAppNames to {}
	repeat with anApp in apps
		set end of persistentAppNames to |file-label| of |tile-data| of anApp
	end repeat
	return persistentAppNames
end dockPersistentAppNames