Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java timer with not-fixed delay

I need a Timer that basicaly does something every t seconds. But I want to be able to modify the timer period at which the timer repeats the task. I wrote something like this:

public Bot() {
    timer = new Timer();
    timer.schedule(new Task(), 1000, moveTime = 1000);          
}

public class Task extends TimerTask {
    @Override
    public void run() {
        System.out.println("Time Passed from last repeat:" + movetime)
        moveTime += 1000;
    }

So, After 1000ms delay the timer starts and repeats every moveTime ms. The problem is even if I increased movetime by 1000, the timer always runs at initial delay(1000) but the value of movetime increases(2000,3000,4000 etc) each time the timer calls run().

Am I missing something or what alternative do I have for repeating a task every 't' second with 't' being variable?

Thanks.

like image 549
Fofole Avatar asked Dec 17 '22 06:12

Fofole


1 Answers

I don't think that the java.util.Timer class supports this.

Something you can do is use the Timer.schedule(TimerTask, int) method that executes your task one after a certain amount of time. When your task gets executed, you can then scheduled a new timer with the new interval you want.

Something like:

int moveTime = 1000;

Timer timer = new Timer();

public Bot(){
    timer.schedule(new Task(), moveTime);
}

public class Task extends TimerTask {
    @Override
    public void run() {
        System.out.println("Time Passed from last repeat:"+movetime)
        moveTime += 1000;
        timer.schedule(new Task(), moveTime)
    }
}
like image 164
Vivien Barousse Avatar answered Dec 18 '22 20:12

Vivien Barousse