How to programmatically shutdown embedded jetty server?
I start jetty server like this:
Server server = new Server(8090);
...
server.start();
server.joi
I found a very clean neat method here
The magic code snippet is:-
server.setStopTimeout(10000L);;
try {
new Thread() {
@Override
public void run() {
try {
context.stop();
server.stop();
} catch (Exception ex) {
System.out.println("Failed to stop Jetty");
}
}
}.start();
Because the shutdown is running from a separate thread, it does not trip up over itself.
Having the ability for a Jetty server to be shutdown remotely through a HTTP request is not recommended as it provides as potential security threat. In most cases it should be sufficient to SSH to the hosting server and run an appropriate command there to shutdown a respective instance of a Jetty server.
The basic idea is to start a separate thread as part of Jetty startup code (so there is no need to sleep as required in one of mentioned in the comment answers) that would serve as a service thread to handle shutdown requests. In this thread, a ServerSocket
could be bound to localhost and a designated port, and when an expected message is received it would call server.stop()
.
This blog post provides a detailed discussion using the above approach.
Try server.setGracefulShutdown(stands_for_milliseconds);
.
I think it's similar to thread.join(stands_for_milliseconds);
.