How would I figure out when the Application is exiting, and then run some code?
you can simply write your code in OnApplicationQuit()
like :
function OnApplicationQuit(){ //do something. }