How do I reset a scheduled task so that it stops and then is rescheduled for the next cycle?
Created Nov 8, 2001
Alex Healey I can do it in the following way
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.
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: