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: https://stackoverflow.com/a/67772583/43615

Let me know if you have any improvement suggestions.

Hi,

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 "com.apple.systemevents" to set theID to ¬
			unix id of (first process whose bundle identifier is bundleID)
		with timeout of timeoutInSeconds seconds
			try
				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
	else
		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: https://stackoverflow.com/a/67821628/43615

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.