I'm trying to make a countdown timer for a educational game that I'm creating (just for studying purposes), but I'm having a little problem.
Summarizing, I just need a timer that:
- Make a 10 seconds countdown.
- Stop when it reaches 0 seconds.
- Throw an exception when it stop (that will be detected by my "View", to show a message to user).
My game have a lot of problems to be solved, each of them must be solved before 10 seconds. I've created a class called "Chronometer" for take care of the problems of my game, but I don't know how I can stop it and throw the desired exception (by the way, this is the best way to contact my view?).
Currently it counts from 10 to 0, but instead stop, it continues and next time it counts from 59 to 0 - and it never stop. How can I fix that?
Current code:
public class Chronometer {
private Timer chronometer;
private DateFormat format = new SimpleDateFormat("ss");
private Calendar calendar = Calendar.getInstance();
private final byte countType;
public static final byte PROGRESSIVE = 1;
public static final byte REGRESSIVE = -1;
public Chronometer(int years, int months, int days, int hours, int minutes, int seconds, byte countType) {
this.chronometer = new Timer();
calendar.set(years, months, days, hours, minutes, seconds);
this.countType = countType;
}
public void starts_chronometer(){
TimerTask task = new TimerTask() {
public void run() {
System.out.println(getTime());
}
};
chronometer.scheduleAtFixedRate(task, 0, 1000);
this.chronometer = null;
}
public int getTime() {
calendar.add(Calendar.SECOND, countType);
return Integer.parseInt(format.format(calendar.getTime()));
}
}
Tried this to throw an exception:
(failed, it throws the exception at the same time chronometer starts.)
public void starts_chronometer() throws Exception {
TimerTask task = new TimerTask() {
public void run() {
System.out.println(getTime());
}
};
chronometer.scheduleAtFixedRate(task, 0, 1000);
this.chronometer = null;
throw new Exception("The time's over!");
}
Tried this to stop when reaches 0 seconds:
(failed, instead of 9...8...7...6 it works something like 9...6...5...3..1)
public void starts_chronometer() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println(getTime());
if(getTime() == 0){
chronometer.cancel();
}
}
};
chronometer.scheduleAtFixedRate(task, 0, 1000);
this.chronometer = null;
}
I already saw a lot of questions in StackOverflow about timers, but none of them help me solve my problem.
Please, help me solve this issue.