How do I reset a scheduled task so that it stops and then is rescheduled for the next cycle?

Alex Healey

I can do it in the following way

  class RemindTask extends TimerTask {
    public void run() {
             System.out.println("run task");
    }
  }
  Timer timer = new Timer();
  timer.schedule(new RemindTask(), 15*1000);
 
//  on reset call timer.cancel()
   timer.cancel();
  
//  and then again create a new Timer
  timer = new Timer();
  timer.schedule(new RemindTask(), 15*1000);

But this would mean wastage of thread resources everytime i want to reset.

[That's really not a very big deal, btw. One thread every 15 seconds is paltry. Perhaps another guru can answer in more detail. -Alex]

Can I somehow reuse the same Timer object? Or do it in a way so that i don't waste too much of resources?


Answer:

Instead of Timer.cancel() call TimerTask.cancel() on the task object which means that the thread can be reused. Then you simply schedule the TimerTask later when you require it.

About | Sitemap | Contact