功能超时

时间:2014-04-22 05:29:24

标签: java

如何在java中实现这样的功能?或者为了更加谨慎,我想为我的功能暂停。

伪代码:

public String aLotOfWork()
{
    return hardWork(); 

    if(hardWork() is still executing after 30 seconds)
           return "TimeOut";


}

我可以使用TimerTask但是我不能将任何值从timer task run()返回到我的上层函数

TimerTask task = new TimerTask() {
    public void run() 
    {
        return ""; // timerTask run must be void.
    }
};
Timer timer = new Timer();
timer.schedule(task, 50000, 1);

2 个答案:

答案 0 :(得分:4)

结帐FutureTask课程。它提供了一个名为get(timeout, timeUnit)的方法。将hardwork任务卸载到FutureTask

public String aLotOfWork() {

  FutureTask task = new FutureTask<String>(new Callable<String>() {

    public String call() {
       return hardwork();
    }
  });

  try {
     return task.get(30, TimeUnit.SECONDS);
  } catch(TimeoutException e) {
     return "Timeout";
  }
  catch(Exception e) {
     return "Timeout"; // or whatever you like
  }

}

答案 1 :(得分:0)

void method() {
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (true) {
        // method logic
        if (System.currentTimeMillis() > endTimeMillis) {
            // do some clean-up
            return;
        }
    }
}