Java: Scheduling a task in random intervals

后端 未结 2 1030
梦毁少年i
梦毁少年i 2020-12-31 19:59

I am quite new to Java and I\'m trying to generate a task that will run every 5 to 10 seconds, so at any interval in the area between 5 to 10, including 10.

I tried

2条回答
  •  天涯浪人
    2020-12-31 20:37

    try

    public class Test1 {
        static Timer timer = new Timer();
    
        static class Task extends TimerTask {
            @Override
            public void run() {
                int delay = (5 + new Random().nextInt(5)) * 1000;
                timer.schedule(new Task(), delay);
                System.out.println(new Date());
            }
    
        }
    
        public static void main(String[] args) throws Exception {
            new Task().run();
        }
    }
    

提交回复
热议问题