Running a work / script when an application closes or quits


I’m using a workflow to swaps different user settings before launching an application. What I would also like to do is backup those user settings after the application has finished. I can do this manually but I really would like to make the process seamless. How can I automatically run a workflow as soon as an application quits?



Hi Nic,

you could do it with this AppleScript, saved as a stay open application.
It checks every 30 seconds the state of the given application without involving the Finder or System Events.
A “emergency exit” is also included, if the application is hanging.
The handler backupUserSettings() represents the code to save the settings

property appname : "TextEdit"
property appRuns : false
property interval : 30

on idle
	set pState to do shell script "/bin/ps -arxo state,comm | /usr/bin/grep " & appname & " | /usr/bin/cut -c 1"
	if appRuns then
		if pState is "" then
			set appRuns to false
		end if
		if pState is not "" then set appRuns to true
	end if
	if pState = "Z" then -- if the application hangs, kill it
		tell application "System Events" to set pid to the unix id of process appname as Unicode text
		do shell script "/bin/kill " & pid
	end if
	return interval
end idle

on backupUserSettings()
	-- do something
end backupUserSettings

Thanks Stefan.

Thats great, it works fine. At the risk of sounding foolish what’s the advantages of avoiding the Finder or System Events?


Sending Apple Events to an application can be quite resource expensive.
I’d recommend to avoid Apple Events especially in an stay open script with a recurrence < 1 minute