0

Hi I am wondering how I could use a timer to destroy a process if it elapses a predefined time period in milisecs.

Currently I have a method which gets the thread from runtime

Runtime runtime = Runtime.getRuntime();

I then create separate process to execute a command using the runtime

 Process process = runtime.exec(comman); //where command is a string with a defined command

I then handle the normal/error output streams before calling:

 process.waitFor(); 

this waits for the process to terminate if it hasn't already.

My question is, how can I go about using a timer to terminate the process before it has finished, i.e. by calling:

 process.destroy;

Basically, if the process works for more than a certain length of time, I want to destroy it prematurely.

I would then throw an InterruptedException if it was destroyed because of over runing.

I was told that using a timer would be the best way to achieve this, but wasnt sure if this was the case?

Any help would be hugely appreciated.

Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68

1 Answers1

0

try

    final Process p = ...
    final Thread mainThread = Thread.currentThread();
    Thread t = new Thread() {
        public void run() {
            try {
                Thread.sleep(1000);
                p.destroy();
                mainThread.interrupt();
            } catch (InterruptedException e) {
            }
        };
    };
    p.waitFor();
    if (mainThread.isInterrupted()) {
        throw new InterruptedException();
    }
    t.interrupt();
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275