title: Process Builder and Process in Java - how to execute a process with a timeout :?
body: <p>I need to execute an external batch file in java with a specific timeout. which means that if the batch execution take longer than specified timeout, i need to cancel the execution.</p>
  
  <p>here is a sample code that i wrote:</p>
  
  <pre><code>public static void main(String[] args) throws IOException, InterruptedException {
      ProcessBuilder p = new ProcessBuilder("c:\\wait.bat", "25");  // batch file execution will take 25 seconds.
      final long l = System.currentTimeMillis();
      System.out.println("starting..." + (System.currentTimeMillis() - l));
      final Process command = p.start();
      System.out.println("started..." + (System.currentTimeMillis() - l));
  
      Timer t = new Timer();
      t.schedule(new TimerTask() {
  
          @Override
          public void run() {
              command.destroy();
          }
      }, 5000);   // it will kill the process after 5 seconds (if it's not finished yet).
      int i = command.waitFor();
      t.cancel();
      System.out.println("done..." + (System.currentTimeMillis() - l));
      System.out.println("result : " + i);
  
      System.out.println("Really Done..." + (System.currentTimeMillis() - l));
  }
  </code></pre>
  
  <p>the batch file "wait.bat" is something like this:</p>
  
  <pre><code>@echo off
  echo starting the process...
  @ping 127.0.0.1 -n 2 -w 1000 &gt; nul
  @ping 127.0.0.1 -n %1% -w 1000&gt; nul
  echo process finished succesfully
  @echo on
  </code></pre>
  
  <p>As you see in the code, batch file will take  25 seconds to finish (first line in main method)  and the Timer will destroy the command  after 5 seconds.</p>
  
  <p>here is the output of my code:</p>
  
  <pre><code>starting...0
  started...0
  done...5000
  result : 1
  Really Done...5000
  BUILD SUCCESSFUL (total time: 25 seconds)
  </code></pre>
  
  <p>as you see in output, the last line ("Really Done...") is executed in 5th second but the application is finished  after 25 seconds.</p>
  
  <p>my question is that : even though i called the destroy method in my timer, why jvm still waiting for the process to be finished ? </p>