Reputation: 7104
if(e.getSource()==continuous)
{
TimerTask task = new TimerTask()
{
public void run()
{
rollthedice();
}
};
timer.schedule(task, java.util.Calendar.getInstance().getTime(), 500);
}
if(e.getSource()==stop)
{
timer.cancel();
}
i hit the continuous button, rollthedice() executes looping twice a second, i hit the stop button rollthedice() stops, what i been looking for is a way to hit the continuous button again after i hit stop to start looping the rollthedice() method again, the stop is to stop the continuous cycle of rollthedice() but i want to be able to hit the continuous button again, idk how to do it, i been looking and looking
Updated thoughts:
Runnable runner = new Runnable(){
public void run()
{
rollthedice();
}
}
if(e.getSource()==continuous)
{
future = scheduler.scheduleAtFixedRate(runner, 0, 500, TimeUnit.MILLISECONDS);
}
if(e.getSource()==stop)
{
future .cancel();
}
Upvotes: 2
Views: 3991
Reputation: 32949
You could use ScheduledThreadPoolExecutor.scheduleAtFixedRate instead. This will allow you to submit a task, cancel it and then submit again.
Upvotes: 1
Reputation: 121971
From the javadoc for Timer.cancel()
:
Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
This means a new instance of Timer
will be required to execute rollthedice()
method again.
Upvotes: 2