Java: Scheduling a task in random intervals

后端 未结 2 1027
梦毁少年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:19

    Create a new Timer for each task instead, like you already do: timer= new Timer();

    And if you want to synchronize your code with your threaded tasks, use semaphores and not sleep(10000). This might work if you're lucky, but it's definitely wrong because you cannot be sure your task has actually finished.

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