How can I change the runtime of a TimerTask at runtime?

How can I change the timer period at runtime?

Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { // read new period period = getPeriod(); doSomething(); } }, 0, period); 
+8
java timer timertask
source share
2 answers

You cannot do this directly, but you can cancel tasks on Timer and transfer them with the required period.

There is no getPeriod method.

+6
source share

You can do it as follows:

 private int period= 1000; private void startTimer() { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { // do something... System.out.println("delay = " + delay); period = 500; // change the period time timer.cancel(); // cancel time startTimer(); // start the time again with a new delay time } }, 0, period); } 
+3
source share

All Articles