我有一个 java 类,当前通过以下方式启动脚本
Process proc = Runtime.getRuntime().exec(" run my script");
出于特定原因,这几乎一直在运行。如果脚本由于某种原因终止,java 类就会重新启动它。
现在我需要偶尔终止该进程。因此,我决定启动一个线程,让它等待特定时间,然后终止该进程。 java 主类或其他类仍然会看到进程终止,然后重新启动它。
我不知道如何让这个线程查看进程并随后经常杀死它。关于如何创建该线程有什么建议吗?需要注意的是,我已经有一段时间没有使用线程了,所以我有点生疏了。
我的类的简单伪代码,用于了解我正在做的事情的基本概念:
Class MyClass{
Process mProc;
main(args){
do{
try{
mProc = Runtime.getRuntime().exec("cmd /C myScript");
mProc.destroy();
} catch(Exception e){
Log(e);
}
} while(true);
最佳答案
I don't know how to get this thread to see the process and the to subsequently kill it every so often.
从 Java 6 开始,这目前并不容易做到。Process
类有一个 waitFor()
方法,但它不会超时,这是悲剧性的在内部它只是调用 wait()
—— 至少在 UnixProcess
中是这样。
您可以做的(有点黑客行为)是在Process
上同步并自己调用wait(timeoutMillis)
。像这样的东西:
Process proc = new ProcessBuilder().command(commandArgs).start();
long startMillis = System.currentTimeMillis();
synchronized (proc) {
proc.wait(someTimeoutMillis);
}
long diff = System.currentTimeMillis() - startMillis;
// if we get here without being interrupted and the delay time is more than
// someTimeoutMillis, then the process should still be running
if (diff >= someTimeoutMillis) {
proc.destroy();
}
问题是存在竞争条件,如果进程在您同步 proc
之前完成,您将永远等待。另一种解决方案是在一个线程中执行 proc.waitFor() 操作,然后在超时到期后在另一个线程中中断它。
Process proc = new ProcessBuilder().command(commandArgs).start();
try {
// this will be interrupted by another thread
int errorCode = proc.waitFor();
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread
Thread.currentThread().interrupt();
// our timeout must have expired so we need to kill the process
proc.destroy();
}
// maybe stop the timeout thread here
另一个选项是使用 proc.exitValue()
,它允许您测试进程是否已执行。不幸的是,如果它还没有完成,它不会返回 -1 或抛出 IllegalThreadStateException
的东西。
关于java线程周期性地杀死一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16464670/