如何只运行Java功能30分钟 [英] How to run java function for only 30 minutes

查看:138
本文介绍了如何只运行Java功能30分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个只能运行30分钟的java函数,并且在30分钟结束时它会执行一些操作。但是,如果符合正确的条件,它也应该可以在给定的时间之前自行终止。

谢谢

解决方案

使用: Timer.schedule(TimerTask,long)

  public void someFunctino(){
//设置超时值
//这将在30分钟内停止该函数
long in30Minutes = 30 * 60 * 1000;
定时器定时器=新的定时器();
timer.schedule(new TimerTask(){
public void run(){
if(conditionsAreMet()){
System.exit(0);
}
}
},in30分钟);

//做这项工作...
....工作n次,它会在30分钟内停住,最多
...代码代码
}


I need to create a java function that will only run for 30 minutes, and at the end of the 30 minutes it executes something. But it should also be able to self terminate before the given time if the right conditions are met. I don't want the function to be sleeping as it should be collecting data, so no sleeping threads.

Thanks

解决方案

Use: 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
}

这篇关于如何只运行Java功能30分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆