按时间间隔测试代码

时间:2011-04-08 07:15:38

标签: java

您好我想在一段时间内运行代码。例如,我希望我的代码可以做这样的事情。

for(every 5 minutes until i say to stop)
 automatically read in new value for x
 automatically read in new value for y

if (x==y)
     //do something

if (x!=y)
     //do something else

4 个答案:

答案 0 :(得分:3)

Timer就是您所需要的。

答案 1 :(得分:0)

天真的版本。您可以考虑使用Timerquartz scheduler

while (!done) {
   try {
     Thread.sleep(5 * 60 * 1000);
     x = readX();
     y = readY();
     if (x == y) {

     } else {

     }
   } catch(InterruptedException ie) {
   }
}

答案 2 :(得分:0)

System.currentTimeMillis的();以毫秒为单位返回系统时间,您可以使用它。 但首先,你需要某种循环。 这是Timer的替代品

public static final int SECONDS = 1000;
public static final int MINUTES = 60 * SECONDS;

boolean quit = false; //Used to quit when you want to..
long startTime = System.currentTimeMillis();

while (!quit) {
    if (System.currentTimeMillis() >= (startTime + (long)5*MINUTES)) {
        //automatically read in new value for x
         //automatically read in new value for y

        if (x==y) {
            //do something
        } else {
        //do something else
        }
        startTime = System.currentTimeMillis(); //reset the timer for the next 5 minutes
    }
}

答案 3 :(得分:0)

怎么样:

Runnable runnable = new Runnable() {
    public void run() {
        // do your processing here
    }
};

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.MINUTES);

如果您想要停止,请致电service.shutdown()