嗨我想在一段時間內運行代碼。例如,我想我的代碼做這樣的事情。測試代碼的時間間隔
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
嗨我想在一段時間內運行代碼。例如,我想我的代碼做這樣的事情。測試代碼的時間間隔
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
Timer是你所需要的。
天真的版本。您可以考慮使用Timer
或quartz scheduler。
while (!done) {
try {
Thread.sleep(5 * 60 * 1000);
x = readX();
y = readY();
if (x == y) {
} else {
}
} catch(InterruptedException ie) {
}
}
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
}
}
如何:
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 {...}而不是 – dominicbri7 2011-04-08 07:18:01