I would like to run a TimerTask in a Timer while some condition is true.
The code I have for the timed event is as follows:
public Double timedAttack(Fighter target){
TimerTask task = new TimerTask() {
public void run() {
attack(target);
}
};
Timer timer = new Timer();
long speed = Math.round(getStats().getSpeed() * 1000);
timer.schedule(task, speed);
return stats.getDamage();
}
This creates a timer, where a fighter must wait it's attack time to execute it's attack against a target. The target will equally be executing this method on the fighter.
The problem I am having is in the method below:
public boolean battle(Fighter target){
while(target.isAlive() && this.isAlive()){
if(isAlive()) {
timedAttack(target);
} else {
break;
}
if(target.isAlive()) {
Double damageDelt = target.timedAttack(this);
target.getStats().increaseFitness(damageDelt);
} else {
break;
}
}
printBattleResult(target);
return battleResult(target);
}
The problem is that, the while loop is constantly creating new timers, which eventually results in a stack overflow.
I would like for it to check if the TimerTask has been executed before running the method timedAttack. I've tried passing back reference to the TimerTask, but there is not built in method to check if the Timer is finished.
I've also tried implementing my own TimerTask which includes an isDone variable to check if the TimerTask is completed, but this has not helped much either since I can't gain access to the TimerTask until after the timedAttack method is executed (at which point a new timer is made anyway)
I also considered created an instance variable of the TimerTask so that I can access its methods / properties at anytime. But since it needs a target passed into it to be attacked, this has also proved to not be very helpful.
If anyone has any helpful suggestions on how to do this, I would greatly appreciate it.
I'm not very familiar with threads / threading, so any advice is helpful.
This is not a duplicate of how to stop a TimerTask, as i'm familiar with how this is done. My question is more specific to creating a TimerTask for each iteration of a loop, if the previous TimerTask has already completed.