Blockquote
I have a Java program with functionality that needs to be run periodically. However, I would like to be able to close the wrapper program (if you're a UNIX person, think Ctrl+C in the terminal window or SIGTERM) without any risk of interrupting the main program processes or threads that the wrapper would start.
At first I was thinking I should have my main program sleep for a certain interval after each round of processing. Then I figured that if the program needs to be closed and is manually interrupted by the user, it might be interrupted while it was processing data and the output files would be chopped or corrupted.
I'm thinking the best way is to write a wrapper program (probably also in Java) that would invoke the main program. If something closes the wrapper, I would like the spawned threads or program instances of my main program to remain open until they are ready to close properly. In addition, at most one instance of the main program should be running at any time.
Here's what I would like my wrapper to do (in pseudocode):
Every n minutes: If an instance of the main program is running, do nothing else spawn an instance of the main program.
On Close: leave main program run to completion if it is running
Should I use the Java Runtime object/library to run my main program (effectively from the command line) or should I change my main program to implement Runnable and have the wrapper program spawn threads running my main program?
EDIT (possible solution?):
Currently I'm thinking of using the Java Runtime object to invoke the main program using the exec function (see http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html and http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html). To determine if the main program is already running I can just use the Process.exitValue() function. If it throws an IllegalThreadStateException then the main program is still running.