Java timer with not-fixed delay

后端 未结 1 1268
南笙
南笙 2021-01-13 16:20

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 somet

相关标签:
1条回答
  • 2021-01-13 17:06

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题