How to add a timeout value when using Java's Runtime.exec()?

前端 未结 17 1781
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  自闭症患者
    2020-11-27 12:15

    For those who can't use the new Java 8 method waitFor(long timeout, TimeUnit unit) (because they are on Android or simply can't upgrade) you can simply rip it from the JDK source code and add it somewhere in your utils file :

    public boolean waitFor(long timeout, TimeUnit unit, final Process process)
                throws InterruptedException
        {
            long startTime = System.nanoTime();
            long rem = unit.toNanos(timeout);
    
            do {
                try {
                    process.exitValue();
                    return true;
                } catch(IllegalThreadStateException ex) {
                    if (rem > 0)
                        Thread.sleep(
                                Math.min(TimeUnit.NANOSECONDS.toMillis(rem) + 1, 100));
                }
                rem = unit.toNanos(timeout) - (System.nanoTime() - startTime);
            } while (rem > 0);
            return false;
        }
    

    The only change I've made to the original one from JDK8 source code is the addition of the Process parameter so that we can call the exitValue method from the process.

    The exitValue method will directly try to return or throw an IllegalThreadStateException if the process has not yet terminated. In that case, we wait the received timeout and terminate.

    The method return a boolean, so if it return false then you know you need to manually kill the process.

    This way seems simplier than anything posted above (expect the direct call to waitFor for sure).

提交回复
热议问题