patternjavaMinor
Custom countdown second timer
Viewed 0 times
countdowncustomtimersecond
Problem
I'm making a card game and I found useful to include a 60 second countdown timer. Here is my approach:
Is this considered clean? How can I test such classes?
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?
Solution
- 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 theFutureTaskthat 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.Code Snippets
this.targetTime = System.nanoTime() + seconds * 1_000_000_000;Context
StackExchange Code Review Q#118669, answer score: 5
Revisions (0)
No revisions yet.