Restarting an app if it has crashed or frozen

I’ve written a script that monitors a particular app, ensuring that it keeps running, even if it’s frozen or has crashed.

I have posted it on the StackOverflow site:

Let me know if you have any improvement suggestions.


I would remove unnecessary variables, and coercions:

-- this script makes sure that a particular program keeps on running,
-- even if it has frozen, in which case it'll be force-quit and relaunched.

property timeoutInSeconds : 2
property appName : "Handbrake"
property bundleID : id of application appName

on idle
	if running of application id bundleID then
		tell application id "" to set theID to ¬
			unix id of (first process whose bundle identifier is bundleID)
		with timeout of timeoutInSeconds seconds
				tell application id bundleID to get documents
			on error errMsg number errNum
				if errNum is -1712 then -- is frozen
					do shell script "/bin/kill -9 " & theID
					repeat while its running of application id bundleID
						delay 0.2
					end repeat
					activate application id bundleID
				end if
			end try
		end timeout
		activate application id bundleID
	end if
	return 60
end idle

That version is quite nice and concise, though it fails at one little detail compared to mine: If there are several versions of the same app, it may launch the wrong one because it ignores the explicit path I may want to specify for it.

I took the liberty of reposting it on StackOverflow. I hope you don’t mind:

This is one of my favorite sites. I often visit it, although I rarely publish anything of my own. Robert Kniazidis is my account there.