Timer in java ,time difference problem
I want to create a timer for my app. The sample code is shown below. When the method datetwo() is called the same time in milliseconds is shown as there in the main method. Please help me out with this
import java.util.Date;
import java.util.Timer;
public class TimerChe {
Timer timer;
static Date date = new Date();
static Date date2 = new Date();
public static void timerMethod(){
new Thread() {
开发者_如何学JAVA public void run() {
try {
while (true) {
sleep(10000);
datetwo();
}
} catch (InterruptedException ex) {
}
}
}.start();
}
public static void datetwo() {
System.out.println ("OK, It's time to do something!") ;
System.out.println("The Time is " + date2.getTime() + " milliseconds since 1970/01/01");
}
public static void main(String args[]) throws Exception {
System.out.println("The Time is " + date.getTime() + " milliseconds since 1970/01/01" );
System.out.println ("Schedule something to do in the mean time.") ;
timerMethod();
}
}
You're creating both Date
s at exactly the same moment, there above as static
variables.
Better replace both the date.getTime()
and date2.getTime()
by new Date().getTime()
or System.currentTimeMillis()
. It will then print the actual time.
Even System.currentTimeMillis() is at milli sec granulariy and its consistency depends upon the jvm implementation (in addition to other factors). My suggestion is to use System.nanoTime() though u might incur some perf penalty.
精彩评论