【发布时间】:2020-01-17 12:34:14
【问题描述】:
我正在尝试使用进程构建器在我的 Java 应用程序中执行 Visual Basic 脚本代码。由于用户提供的脚本可能无法及时完成其执行,我想提供限制此执行时间的方法。在下面的代码中,您可以看到我的逻辑,但它并没有真正做到它应该做的事情。我怎样才能让这个等待工作以限制执行时间?
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
}
【问题讨论】:
-
“但它并没有真正做到它应该做的事情”你认为它应该做什么,而它又做了什么?
-
当脚本执行时间超过waitfor方法指定的时间时,应该终止其执行。我看不出有任何理由说明上面的文字不清楚。
-
The Javadoc of
waitFor表示“如有必要,使当前线程等待,直到此 Process 对象表示的子进程终止,或指定的等待时间过去。” (强调补充)。如果时间过去了,它不会说进程终止。
标签: java multithreading processbuilder java-threads