views:

31

answers:

2

My app has a feature like the BlackBerry Stopwatch application:
A label displaying the time, updated every 100 milliseconds.

I've used a separate thread for a Timer which schedules a TimerTask to update the label.

Everything works fine, but I've noticed the the stopwatch in my app runs a little bit slower than the built-in BlackBerry stopwatch -- it loses 1 second per minute.
Sometimes the timer in my app halts for a while, about 300-500 milliseconds, for unknown reasons.

What could make the Timer in my app slower than the BlackBerry stopwatch?
Any suggestions to create a stopwatch which run as smoothly as the BlackBerry stopwatch?

+2  A: 

I guess you shouldn't rely on adding time periods. So 60 times sleep for 1 second should not be treated as minute.

Instead sleep for a second and after waking up check the system time.

Grzegorz Oledzki
I'd try your suggestion Grzegorz, thank you.
Tuyen Nguyen
+3  A: 

You should use System.currentTimeMillis() to compute the time. The Timer does not guarantee when it will execute - the guarantee is that the specified time is the minimum delay until execution starts, but there is no maximum, as you've noticed. So use the Timer to schedule UI updates, but calculate the elapsed time using System.currentTimeMillis().

Michael Donohue
Michael, I've used System.currentTimeMillis() and my stopwatch now works precisely as expected. Thank you for your valuable answer. Cheers !!!
Tuyen Nguyen