public static int waitForFinish(final ExternalExecutor myExecutor, final int timeout) { synchronized (myExecutor) { try { long timeoutMillis = 1000L * timeout; long startTime = System.currentTimeMillis(); myExecutor.start(); while (System.currentTimeMillis() - startTime < timeoutMillis) { // reduce the timeout to the residual of the timeout timeoutMillis -= System.currentTimeMillis() - startTime; myExecutor.wait(timeoutMillis); // wait can return for different reasons if (myExecutor.getState().equals(Thread.State.TERMINATED)) { break; } } if (!myExecutor.getState().equals(Thread.State.TERMINATED)) { myExecutor.timeout = true; myExecutor.interrupt(); myExecutor.join(); } } catch (InterruptedException e) { log.info("ExeRunner.run() got interrupted while waiting for timeout", e); } } return myExecutor.erg; }
/** * Runs an executable and waits until the executable finishes or until * a certain amount of time has passed (timeout). * * @param cmd The system command to execute. E.g. "/bin/sh some-script.sh arg1 arg2" * @param stdoutFileName specifies the file where stdout of the executable is redirected to. * @param timeout A timeout in seconds. If the executable is still running after * <code>timeout</code> seconds, the executable is stopped and this method returns. * @param workingDirectory the working directory to be used when calling the command * @return exit-code of the executable. */ public static int run(final String cmd, final String stdoutFileName, final int timeout, final String workingDirectory) { final ExternalExecutor myExecutor = new ExternalExecutor(cmd, stdoutFileName, workingDirectory); return waitForFinish(myExecutor, timeout); }
public static int run(final String[] cmdArgs, final String stdoutFileName, final int timeout, final String workingDirectory) { final ExternalExecutor myExecutor = new ExternalExecutor(cmdArgs, stdoutFileName, workingDirectory); return waitForFinish(myExecutor, timeout); }