How can I change period of Timer at runtime?
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// read new period
period = getPeriod();
doSomething();
}
}, 0, period);
You can do it like this:
private int period= 1000; // ms
private void startTimer() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// do something...
System.out.println("period = " + period);
period = 500; // change the period time
timer.cancel(); // cancel time
startTimer(); // start the time again with a new period time
}
}, 0, period);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With