\$\begingroup\$
\$\endgroup\$
1
I'm making a card game and I found useful to include a 60 second countdown timer. Here is my approach:
import java.util.Timer;
import java.util.TimerTask;
public class SecondTimer {
private Timer timer;
private int countDown;
private int secondsLeft;
public SecondTimer() {
timer = new Timer();
}
public void reset() {
secondsLeft = countDown;
// Decrease seconds left every 1 second.
timer.schedule(new TimerTask() {
@Override
public void run() {
secondsLeft--;
if (secondsLeft == 0) {
timer.cancel();
}
}
}, 0, 1000);
}
public void setCountDown(int seconds) {
this.countDown = seconds;
}
public int getSecondsLeft() {
return secondsLeft;
}
}
Is this considered clean? How can I test such classes?
asked Feb 2, 2016 at 18:29
-
1\$\begingroup\$ What is hooked up to this code? How is the remaining time displayed? Is it supposed to trigger some action at the end of 60 seconds? \$\endgroup\$200_success– 200_success2016年02月02日 22:27:51 +00:00Commented Feb 2, 2016 at 22:27
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- Avoid using
java.util.Timer
. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use aScheduledExecutorService
. - When changing to a
ScheduledExecutorService
, don't cancel or shutdown yourScheduledExecutorService
, instead cancel theFutureTask
that you will get when scheduling a task. - Don't decrease a counter once a second. Nothing guarantees that it will be called with exactly 1000 ms periodicity.
In your reset
method, use System.nanoTime()
(not System.currentTimeMillis
) to calculate when the time is up, such as:
this.targetTime = System.nanoTime() + seconds * 1_000_000_000;
Then calculate in getSecondsLeft
, by using System.nanoTime()
again, how many seconds remain until the target nanosecond value has been reached.
answered Feb 2, 2016 at 21:17
lang-java