为执行多个路径的方法添加超时

时间:2016-12-19 15:31:34

标签: java recursion timeout

我有以下方法定义

   private void pollForStatus() throws  InterruptedException {

            if (state.equals("running")) {
                log.debug("Task still running, Polling again ..");
                TimeUnit.SECONDS.sleep(1);
                pollForStatus();
            }

            else if (state.equals("complete") ) {
                return;
            }

            else if (state.equals("stopped")) {
            {
                    // Report error state

            }

}

现在为了让'pllForStatus'在某些情况下不继续执行,我想为递归添加超时。如何在Java(7)中实现这一目标?

1 个答案:

答案 0 :(得分:0)

long futureTime = System.currentTimeMillis + yourInterval;
private void pollForStatus() throws InterruptedException {

    if (state.equals("running")) {
        log.debug("Task still running, Polling again ..");
        TimeUnit.SECONDS.sleep(1);

        //havnt reached cut off time yet, loop again
        if(System.currentTimeMilis() < futureTime){
            pollForStatus();
        }
    } else if (state.equals("complete")) {
        return;
    } else if (state.equals("stopped")) {

        // Report error state

    }


}