Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change my TimerTask's execution period at runtime?I

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);
like image 268
VextoR Avatar asked Jun 29 '11 11:06

VextoR


1 Answers

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);
}
like image 76
Bahramdun Adil Avatar answered Sep 25 '22 21:09

Bahramdun Adil