Changing timer interval dynamically in Java 1.4

1.2k Views Asked by At

I have a timer task as shown below:

long timerSec = 5000;

TimerTask task1 = new TimerTask()
{   
    public void run()
    {
        //Some code...
        System.out.println("Timer task...");
    }
};

And a timer object as shown below:

Timer readFileTimer = new Timer();

I scheduled a task with 5 secs period between two successive task executions.

readFileTimer.scheduleAtFixedRate(task1, 0, timerSec);

Below line of code assigns new time period. I want to change the time period from 5 secs to n-secs (lets say 10 secs w.r.t. timerSec value).

timerSec = CalculateTimeForUpgrade(); //Get new timer interval period.

I tried below code, but didn't get the expected result.

readFileTimer.scheduleAtFixedRate(task1, 0, timerSec);

Please help. Thanks in advance.

1

There are 1 best solutions below

0
Pablo Gallego Falcón On

Instead of starting the task at a fixed interval from the beginning, reschedule the task every time you finish it. Something like this:

    final Timer readFileTimer = new Timer();
    readFileTimer.schedule(new MyTimerTask(), 0);

    .......

    private class MyTimerTask extends TimerTask() {
        @Override
        public void run() {
            // Some code...
            System.out.println("Timer task...");
            if (readFileTimer!=null)
                readFileTimer.schedule(new MyTimerTask(), CalculateTimeForUpgrade());
        }
    }