Ahm*_*ğlu -1 java multithreading processbuilder java-threads
我正在尝试使用流程构建器在我的 Java 应用程序中执行可视化基本脚本代码。由于用户提供的脚本可能无法及时完成执行,我想提供一种方法来限制此执行时间。在下面的代码中,你可以看到我的逻辑,但它并没有真正做它应该做的。我怎样才能使这个等待工作以限制执行时间?
private void run(String scriptFilePath) throws ScriptPluginException {
BufferedReader input = null;
BufferedReader error = null;
try {
ProcessBuilder p = new ProcessBuilder("cscript.exe", "//U", "\"" + scriptFilePath + "\"");
String path = "";
if (scriptFilePath.indexOf("/") != -1) {
path = scriptFilePath.substring(0, scriptFilePath.lastIndexOf("/"));
}
path += "/" + "tempvbsoutput.txt";
p.redirectOutput(new File(path));
Process pp = p.start();
try {
pp.waitFor(executionTimeout, TimeUnit.MINUTES);
} catch (InterruptedException e) {
SystemLog.writeError(jobId, ScriptConsts.COMPONENT_ID, "VBScriptExecutor", "run", 80401104,
"VB Script executes fail.");
}
if (!pp.isAlive()) {
pp.getOutputStream().close();
}
// rest of the code flow
Run Code Online (Sandbox Code Playgroud)
}
Process.waitFor(long, TimeUnit)等待直到进程终止或指定的时间过去 ( Javadoc )。返回值指示进程是否退出。
if (process.waitFor(1, TimeUnit.MINUTES)) {
System.out.println("process exited");
} else {
System.out.println("process is still running");
}
Run Code Online (Sandbox Code Playgroud)
waitFor() 时间过去后不会终止进程。
如果要终止子进程,请使用destroy()或destroyForcibly()。