3
\$\begingroup\$

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?

\$\endgroup\$
  • 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 Feb 2 '16 at 22:27
5
\$\begingroup\$
  • 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.
  • 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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.