Timestamp, timers, time question
I've been Googling Java timestamps, timers, and anything to do with time and Java. I jus开发者_运维百科t can't seem to get anything to work for me.
I need a timestamp to control a while loop like the pseudo-code below
while(true)
{
while(mytimer.millsecounds < amountOftimeIwantLoopToRunFor)
{
dostuff();
}
mytimer.rest();
}
Any ideas what data type I could use; I have tried Timestamp, but didn't seem to work.
Thanks Ciarán
Do something like:
long maxduration = 10000; // 10 seconds.
long endtime = System.currentTimeMillis() + maxduration;
while (System.currentTimeMillis() < endtime) {
// ...
}
An (more advanced) alternative is using java.util.concurrent.ExecutorService
. Here's an SSCCE:
package com.stackoverflow.q2303206;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String... args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.SECONDS); // Get 10 seconds time.
executor.shutdown();
}
}
class Task implements Callable<String> {
public String call() throws Exception {
while (true) {
// ...
}
return null;
}
}
精彩评论