views:

91

answers:

2

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() {
            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();
    } 
}
+3  A: 

You're creating both Dates 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.

BalusC
thanks BalusC..
javatechi
+1 - the point is that `date.getTime()` returns the time recorded in the `Date` object, not the current time.
Stephen C
+1  A: 

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.

Pangea