Java: scheduling tasks at random intervals

I'm new to Java. I'm trying to generate a task that runs every 5 to 10 seconds, so any time interval between 5 and 10, including 10

I've tried a few things, but I haven't had any work so far My recent efforts are as follows:

timer= new Timer();
Random generator = new Random();
int interval;

//The task will run after 10 seconds for the first time:
timer.schedule(task,10000); 

//Wait for the first execution of the task to finish:               
try {
    sleep(10000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}

//Afterwards,run it every 5 to 10 seconds,until a condition becomes true:
while(!some_condition)){
    interval = (generator.nextInt(6)+5)*1000;
    timer.schedule(task,interval);

    try {
        sleep(interval);
    } catch(InterruptedException ex) {
    ex.printStackTrace();
    }
}

"Task" is a TimerTask What I get is:

Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled

I learned from here that TimerTask cannot be reused, but I don't know how to fix it By the way, my TimerTask is very complex and lasts at least 1.5 seconds

Any help will be greatly appreciated, thank you!

resolvent

Solution

attempt

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();
    }
}

The above is the whole content of Java: scheduling tasks at random intervals collected by programming house. I hope this article can help you solve the program development problems encountered by Java: scheduling tasks at random intervals.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>