呼叫新的Thread 來監控 cmd
主要目的是控管時間和失敗處理的一些方法,
以及添加失敗時從新嘗試(最多3次)。
public static int executeCommandLine(String inputFilePath, String outputFilePath,String[] cmd)
throws IOException, InterruptedException, TimeoutException {
//這邊設定要執行的指令字串
cmd = new String[]{"sudo", "gs", etc...=" + outputFilePath, inputFilePath};
System.out.println(String.join(" ", cmd));
//紀錄執行次數用的變數
int count = 0;
do
{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmd);
Worker worker = new Worker(process);
worker.start();
try {
//設定等待計秒,超過 5 秒 中斷 worker
worker.join(5000);
count++;
//執行成功 return worker.exit(成功下面就部會執行了)
if (worker.exit != null){
return worker.exit;
}else {
System.out.println("cmd wait time is too long to fail");
}
} catch(InterruptedException ex) {
//中斷 worker
worker.interrupt();
Thread.currentThread().interrupt();
throw ex;
} finally {
process.destroy();
}
}
//最多執行3次
}while(count<2);
throw new TimeoutException();
}
public static class Worker extends Thread {
private Process process;
private Integer exit;
private Worker(Process process) {
this.process = process;
}
public void run() {
try {
exit = process.waitFor();
} catch (InterruptedException ignore) {
return;
}
}
}
PS.參考網址:http://stackoverflow.com/questions/808276/how-to-add-a-timeout-value-when-using-javas-runtime-exec