[英]kill process after some time in java
我想在一段時間后終止某個進程,如果該進程沒有響應,我使用了此代碼,但我無法達到同樣的效果
long start = System.currentTimeMillis(); long end = start +60000;
1 while (System.currentTimeMillis() < end)
2 {
3 Connection.execute(function); // execute
4 break; // break if response came
5 }
6 if(System.currentTimeMillis() > end)
7 {
8 close connection; // close connection if line no 3 will not responded
9 }
請在同一時間幫助我
由於調用Connection.execute()處於阻塞狀態,因此主線程將一直阻塞,直到執行為止。在這種情況下,如果我們要在阻塞主線程時關閉連接,則必須關閉其他線程中的連接。 在這種情況下,也許我們可以使用Timer和TimerTask。 我試圖編寫如下代碼,可能是您可以做到的。
Timer timer = new Timer();
while (System.currentTimeMillis() < end) { //In any case, this loop runs for only one time, then we can replace it with IF condition
CloseConnectionTask task = new CloseConnectionTask(Connection);
timer.schedule(task, end); // Task will be excuted after the delay by "end" milliseconds
Connection.execute(function); // execute
task.cancel(); //If the excute() call returns within time ie. "end" milliseconds, then timerTask will not get executed.
break; // break if response came//
}
timer.cancel(); // If you have no more scheduling tasks, then timer thread should be stopped.
下面是TimerTask的實現:
class CloseConnectionTask extends TimerTask {
private Connection con;
public CloseConnectionTask(Connection con) {
this.con = con;
}
@Override
public void run() {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
注意:我還有一句話要說,在您的while循環中,如果對Connection.execute()的調用成功,則您將中斷循環。 因此,我觀察到的是,在任何情況下,循環僅執行一次,如果是這種情況,則應使用IF(同樣,在提供的代碼中也是如此,您的要求可能有所不同)。 希望對您有所幫助。 如果您對此有其他想法,請分享。 我的答案是基於此鏈接 ,很好的信息。 在那兒。
這樣,這將無濟於事,我認為您應該實現線程來實現這一目標
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.