2013-05-09 103 views
0

我目前通過Java線程週期性地殺死一個過程

Process proc = Runtime.getRuntime().exec(" run my script"); 

揭開序幕腳本的具體原因,這幾乎一直運行的Java類。如果腳本因爲任何原因而死,那麼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); 
+0

請避免使用僞代碼。這是馬虎,可以省略重要的細節(如「r」)。 – Michael 2013-05-09 14:52:29

+0

您可以簡單地安排任務在需要時運行並調用'myClass.mProc.destroy();' – assylias 2013-05-09 14:56:15

+0

爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-05-09 14:56:26

回答

1

我不知道怎麼去這個線程看到過程和隨後殺死它每隔一段時間。

這是當前不容易做到如Java 6的Process類有一個waitFor()方法,但它沒有考慮這是悲慘的因爲內部它只是調用wait()超時 - 至少在UnixProcess

你可以做什麼,這是一個黑客的同步Processwait(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