简体   繁体   中英

kill process after some time in java

i want to terminate some process after some time if that process will not responded i used this code but i am not able to achive the same

 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 }

kindly help me on the same

As the call Connection.execute() is blocking, so main thread will be blocked until it executes, SO in that case if we want to close the connection when the main thread is blocked , we have to close connection in some other thread. May be we can use Timer & TimerTask in this case. I tried to write some code as below, May be you can some thing like that.

        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.

Below is TimerTask implementation:

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();
        }
    }
}

Note: I have one more thing to say, In your while loop, If the call to Connection.execute() successful, then you break from the loop. So what I have observed, In any case your loop is executing only once, If this is the case, then you should use IF(again its what I have seen in the provided code, you requirement may be different). Hope it may help you. If you have other thoughts on this, please share. My answer is based on this link , Good info. is there.

这样,这将无济于事,我认为您应该实现线程来实现这一目标

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM