Wednesday 7 December 2011

Execute command line process from Java with timeout

In order to execute command line process from Java with timeout, please use following snippet:

 public static void executeCommand(String command, long timeoutInSeconds) throws Exception {
  ExecutorService service = Executors.newSingleThreadExecutor();
  Process process = Runtime.getRuntime().exec(command);
  try {
   Callable call = new CallableProcess(process);
   Future future = service.submit(call);
   int exitValue = future.get(timeoutInSeconds, TimeUnit.SECONDS);
   if (exitValue != 0) {
    throw new Exception("Process did not exit correctly");
   }
  } catch (ExecutionException e) {
   throw new Exception("Process failed to execute", e);
  } catch (TimeoutException e) {
   process.destroy();
   throw new Exception("Process timed out", e);
  } finally {
   service.shutdown();
  }
 }
 
 private static class CallableProcess implements Callable {
 
  private Process p;
 
  public CallableProcess(Process process) {
   p = process;
  }
 
  public Integer call() throws Exception {
   return p.waitFor();
  }
 }
  

No comments:

Post a Comment