Programmatically catch app opening / closing
You can obtain notifications of applications being launched and quit. Apple's TN2050: Observing Process Lifetimes Without Polling provides the detail.

The best method for general purpose tracking is with NSWorkspace and its NSWorkspaceDidLaunchApplicationNotification and NSWorkspaceDidTerminateApplicationNotification notifications.

I do not believe there is a trivial means to implement these TN2050's methods in AppleScript. You will likely need to write a small Objective-C/Cocoa application or use a third party tool.