Google+ Badge

Thursday, June 7, 2012

Sync one minute Java timer to the current time

I am working on a patient scheduler and I need to draw a line across the screen indicating the current time. Helps them not create appointments in the past. We also have a clock on screen via the Jide status bar. It was driving me crazy that the line moved down or across screen but not in sync with clock. That means the line might move at the 20 second mark of the clock all depending on when you started up the program. Turns out it was adding one line of code to get them within one second of being in sync which made me happy.

timer = new Timer(60000, this);
// Force initial delay to sync within a second of current clock
Calendar cal = Calendar.getInstance();
timer.setInitialDelay((60 - cal.get(Calendar.SECOND)) * 1000);
timer.setRepeats(true);
timer.start();

It is the one line of code setting the initial delay that solves the problem. After that the timer triggers every 60 seconds and away we go. Just makes things look so much cleaner.