Java fixed delay timer

I need a Timer that basicaly does something every t seconds. But I want to be able to change 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 a delay of 1000 ms, the timer starts and repeats every moveTime ms. The problem even is that if I increase moveTime by 1000, the timer always starts with an initial delay (1000), but the value of moveTime increases (2000, 000, 4000, etc.) Each time the timer calls run() .

Am I missing something or what do I have to repeat the task every 't' second, when 't' is a variable?

Thanks.

+4
source share
1 answer

I do not think the java.util.Timer class supports this.

Something you can do is use the Timer.schedule(TimerTask, int) method, which performs your task after a certain amount of time. When your task is complete, you can schedule a new timer with the new interval you want.

Sort of:

 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) } } 
+12
source

Source: https://habr.com/ru/post/1384714/


All Articles