# Custom countdown second timer

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;

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.
@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?

• 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? – 200_success Feb 2 '16 at 22:27

• Avoid using java.util.Timer. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use a ScheduledExecutorService.
• When changing to a ScheduledExecutorService, don't cancel or shutdown your ScheduledExecutorService, instead cancel the FutureTask that you will get when scheduling a task.
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.