Doing something before program exit
Check out the atexit
module:
http://docs.python.org/library/atexit.html
For example, if I wanted to print a message when my application was terminating:
import atexit
def exit_handler():
print 'My application is ending!'
atexit.register(exit_handler)
Just be aware that this works great for normal termination of the script, but it won't get called in all cases (e.g. fatal internal errors).
C: Doing something when the program exits
look into the atexit
API of the C standard library.
How to run code before program exit?
Try the ProcessExit event of AppDomain
:
using System;
class Test {
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnProcessExit);
// Do something here
}
static void OnProcessExit (object sender, EventArgs e)
{
Console.WriteLine ("I'm out of here");
}
}
Why does this program exit before invoking my then clause?
As in the answer to your previous question, you are using a Promise, which is guaranteed to skip over the request and response. By passing in those two function
s, you are offering your execution environment (presumably Node) callbacks that it can call once it successfully completes the request. Because you're accessing a remote server, this will take some time, typically in the tens or hundreds of milliseconds.
If you don't instruct Node otherwise, it will terminate when it reaches the end of your script. This may not be in time for the library to invoke your callback. As in this NodeJS issue, you can use a top-level await
function, which pauses execution of your program to wait for the callback.
try {
let success = await request(options);
console.log(success);
} catch (error) {
console.log('noob!');
}
See also: Node exits without error and doesn't await promise (Event callback)
Calling function when program exits in java
You can add a shutdown hook to your application by doing the following:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// what you want to do
}
}));
This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.
Please note the caveats though!
Running code on program exit in Java
Use Runtime.getRuntime().addShutdownHook(Thread)
.
Doing a cleanup action just before Node.js exits
UPDATE:
You can register a handler for process.on('exit')
and in any other case(SIGINT
or unhandled exception) to call process.exit()
process.stdin.resume();//so the program will not close instantly
function exitHandler(options, exitCode) {
if (options.cleanup) console.log('clean');
if (exitCode || exitCode === 0) console.log(exitCode);
if (options.exit) process.exit();
}
//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
Related Topics
Separation of Business Logic and Data Access in Django
Is There a Matplotlib Equivalent of Matlab's Datacursormode
Matplotlib Fill Between Multiple Lines
Why Doesn't a Python Dict.Update() Return the Object
Pylab.Ion() in Python 2, Matplotlib 1.1.1 and Updating of the Plot While the Program Runs
How Include Static Files to Setuptools - Python Package
Which Is the Easiest Way to Simulate Keyboard and Mouse on Python
Postponing Functions in Python
Sorting a List of Dot-Separated Numbers, Like Software Versions
Python's Insert Returning None
Naturally Sorting Pandas Dataframe
Why Does Sys.Exit() Not Exit When Called Inside a Thread in Python
How to Avoid Explicit 'Self' in Python
Difference Between Numpy Dot() and Python 3.5+ Matrix Multiplication @