2
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();

}
1
  • Per hmjd's response, create a new Timer just before calling schedule. Commented Oct 26, 2012 at 15:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

what is a way to make a new instance for the loop
1

You could use ScheduledThreadPoolExecutor.scheduleAtFixedRate instead. This will allow you to submit a task, cancel it and then submit again.

10 Comments

i tried this i got errors i made future the Timer, scheduler and TimeUnit cannot be resolved it says
All of those classes are part of the Java language. Did you forget to add the imports?
i cut out the Timer, runner is how it is above, scheduler is the ScheduledThreadPoolExecutor, i have no future, and idk what to do to stop the scheduler, i new to this
Post what you now have. You don't stop the scheduler, you cancel the Future.
ScheduledThreadPoolExecutor scheduler; scheduler = new ScheduledThreadPoolExecutor(1); Runnable runner = new Runnable(){ public void run() { rollthedice(); } }; if(e.getSource()==continuous) { scheduler.scheduleAtFixedRate(runner, 0, 500, TimeUnit.MILLISECONDS); } if(e.getSource()==stop) { scheduler.shutdown(); } i want the stop button to stop the scheduler and then when i click continuous to start it again
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.