Java JDK 1.5 Example、外部プロセス実行のタイムアウト

2021年2月27日

JDK 1.5 Processクラスにはタイムアウト付きwaitForがない

Javadoc Process waitFor()

1.8以降はタイムアウト付きwaitForがある。
Javadoc Process waitFor()タイムアウト付き

Example Code

package ExampleRunShell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class Main {
package ExampleRunShell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        StringBuffer output = new StringBuffer();
        class TimeOutTimerTask extends TimerTask {
            private Process process;
            public boolean isTimeout = false;

            public TimeOutTimerTask(Process process) {
                    this.process = process;
            }

            @Override
            public void run() {
                System.out.println("Timeout!!");
                isTimeout = true;
                process.destroy();
            }
        }
        Process process;
        try {
            process = Runtime.getRuntime().exec("ping");
            
            TimeOutTimerTask timeOutTimerTask = new TimeOutTimerTask(process);
            Timer timer = new Timer("Shell Exec Timeout Timer");
            timer.schedule(timeOutTimerTask, TimeUnit.SECONDS.toMillis(60));
//            timer.schedule(timeOutTimerTask, 1);
            
            int result = process.waitFor();
            System.err.println(result);
            timer.cancel();
            if(timeOutTimerTask.isTimeout == false) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                while((line = bufferedReader.readLine()) != null) {
                    output.append(line + "\n");
                }
                System.out.println(output.toString());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java

Posted by shi-n