2011-04-08 46 views
1

嗨我想在一段時間內運行代碼。例如,我想我的代碼做這樣的事情。測試代碼的時間間隔

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 
+0

首先,你應該使用if(x == y){...} else {...}而不是 – dominicbri7 2011-04-08 07:18:01

回答

3

Timer是你所需要的。

0

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

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

    } else { 

    } 
    } catch(InterruptedException ie) { 
    } 
} 
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 
    } 
} 
+0

謝謝你這麼快速的迴應! – Aaron 2011-04-08 07:38:02

+0

不應該有一個睡眠或在這個? – Erik 2011-04-08 09:11:03

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()