Java的Runtime可以执行命令行脚本,某些特定场合需要对脚本的执行时间进行控制,防止脚本某些异常情况下,一直未能正确结束,导致Java主进程挂起。本文的程序对这一过程进行了控制
Java代码
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassCommandUtils {
privatestaticLogger logger = LoggerFactory.getLogger(CommandUtils.class);
//default time out, in millseconds
publicstaticfinalintDEFAULT_TIMEOUT =10*1000;
publicstaticfinalintDEFAULT_INTERVAL =1000;
/**
* Executes the specified command in a separate process. The method then blocks until the process returned.
* If an error arises during the execution or if the exeecuted process returned an non-null return code,
* the content of the process' stderr is returned to the caller. If the execution is fine, null is returned.
*
* @param command String
* @return CommandResult
*/
publicstaticCommandResult exec(String command) {
longstart = System.currentTimeMillis();
longlast;
CommandResult commandResult =newCommandResult();
try{
Process process = Runtime.getRuntime().exec(command);
process(process, commandResult);
if(process !=null) {
process.destroy();
}
last = (System.currentTimeMillis() - start) /1000;
logger.info("Execute command ["+ command +"], last ["+ last +"] s.");
}catch(Exception e) {
last = (System.currentTimeMillis() - start) /1000;
String error ="Execute command ["+ command +"] last ["+ last +"] s, failed ["+ e.getMessage() +"]";
log