如何运行java函数只需30分钟

Ang*_*lev 7 java time function timer

我需要创建一个只运行30分钟的java函数,并在30分钟结束时执行一些操作.但如果符合正确的条件,它也应该能够在给定时间之前自行终止.我不希望函数休眠,因为它应该收集数据,所以没有睡眠线程.

谢谢

Osc*_*Ryz 5

使用:Timer.schedule(TimerTask,long)

public void someFunctino() {
    // set the timeout    
    // this will stop this function in 30 minutes
    long in30Minutes = 30 * 60 * 1000;
    Timer timer = new Timer();
    timer.schedule( new TimerTask(){
          public void run() {
               if( conditionsAreMet() ) { 
                   System.exit(0);
                }
           }
     },  in30Minutes );

     // do the work... 
      .... work for n time, it would be stoped in 30 minutes at most
      ... code code code
}
Run Code Online (Sandbox Code Playgroud)