Safe/graceful shutdown of Java application running through Windows Task Scheduler
<p>I'm trying to write a simple service manager in Java for some servers my community runs. The general idea is that a server side application launches a server and hooks into its console's streams though the Process class, relaying it to client applications that can be run on a user session through RDP or even remotely. </p>

<p>Now, I've got the networking and the relaying working fine; that stuff is relatively straightforward. The issue I'm having is getting the servers to shutdown safely when the server (or just the task) reboots.</p>

<p>I got the impression that Runtime's shutdown hooks would be the proper way to handle this, but they don't seem to be working.</p>

<p>Full code of my console wrapper class: <a href="http://pastebin.com/vM3PQ9zE" rel="nofollow">http://pastebin.com/vM3PQ9zE</a></p>

<p>This is the method that starts the service with class fields added for clarity:</p>

<pre><code>private final ProcessBuilder builder;
private Process process;
private boolean stopped = false;
private HashSet&lt;ConsoleListener&gt; listeners;
private PrintStream commandStream;
private InputHandler handler;
private Thread shutdownTask;

public void start() throws IOException {
    if (this.hasStarted())
        throw new IllegalStateException(
                "This process has already been started once.");

    this.process = this.builder.start();

    for (ConsoleListener l : this.listeners) {
        l.onStart(new ConsoleEvent(this));
    }

    this.handler = new InputHandler(this.process.getInputStream());
    new Thread(this.handler).start();

    this.commandStream = new PrintStream(this.process.getOutputStream());

    Runtime.getRuntime().addShutdownHook(
            this.shutdownTask = new Thread(new ShutdownListener()));
}
</code></pre>

<p>The class ShutdownListener is defined inline as:</p>

<pre><code>private class ShutdownListener implements Runnable {
    @Override
    public void run() {
        ConsoleApplication.this.nuke();
    }
}
</code></pre>

<p>The nuke method is defined as:</p>

<pre><code>public void nuke() {
    this.process.destroy();
}
</code></pre>

<p>Now I eventually want the wrapper to be able to send proper commands for safe shutdown, but it seems that its not even capable of forcing the process closed. I've tried moving my shutdown hooks around, and testing seems to reveal that nuke() is never being called. </p>

<p>Any help would be greatly appreciated.</p>

<p>Notes:</p>

<p>I'm not attached to Task Scheduler. It just seems to be the easiest way to handle starting on server boot. If there is a solution that doesn't involve Task Scheduler, I'd love to hear it.</p>
