2015年11月5日 星期四

可設定 Timeout 之 Java Command Line Executor



import java.util.concurrent.TimeoutException;

public class TimeoutCommandLine {
    public static int executeCommandLine(String commandLine, long timeout)
            throws
Exception {
        Process process = Runtime.getRuntime().exec(commandLine);
        Worker worker = new Worker(process);
        worker.start();
        try {
            worker.join(timeout);
            if (worker.exit != null) {
                return worker.exit;
            } else {
                throw new TimeoutException();
            }
        } catch (InterruptedException ex) {
            worker.interrupt();
            Thread.currentThread().interrupt();
            throw ex;
        } finally {
            process.destroy();
        }
    }

    private static class Worker extends Thread {
        private final Process process;
        private Integer exit;

        private Worker(Process process) {
            this.process = process;
        }

        public void run() {
            try {
                exit = process.waitFor();
            } catch (InterruptedException ignore) {
                return;
            }
        }
    }
}
使用方式:
TimeoutCommandLine.executeCommandLine("rsh xxxHost hostname", 2000);
設定執行 command rsh xxxHost hostname , 超過 2秒 沒回應即回傳 TimeoutException。

沒有留言:

張貼留言