java 调用 shell 超时时间_Java执行Shell脚本超时控制

Java通过Runtime执行命令行脚本时,为防止脚本异常导致进程挂起,可以设置超时控制。本文的Java代码示例展示了如何在执行命令行脚本时进行超时控制,当超过预设时间限制时,脚本将被强制结束。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值