Java 按时间间隔测试代码

Java 按时间间隔测试代码,java,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 是你所需要的。天真版。你可以考虑计时器< /> >或反之。 S

嗨,我想在一段时间内运行代码。例如,我想让我的代码做这样的事情

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

是你所需要的。

天真版。你可以考虑<代码>计时器< /> >或反之。

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

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
    }
}
那么:

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

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

当您想停止时,调用
service.shutdown()

首先,您应该使用if(x==y){…}else{…},而不是应该在这里面有睡眠或其他什么吗?
Runnable runnable = new Runnable() {
    public void run() {
        // do your processing here
    }
};

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