Java: Scheduling a task in random intervals

11,657

Solution 1

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

Solution 2

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.

Share:
11,657
idpolitis
Author by

idpolitis

Updated on June 17, 2022

Comments

  • idpolitis
    idpolitis almost 2 years

    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 several things but nothing is working so far. My latest effort is below:

    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 understand from here that a TimerTask cannot be reused, but I am not sure how to fix it. By the way the my TimerTask is quite elaborate and lasts itself at least 1,5 seconds.

    Any help will be really appreciated, thanks!

  • idpolitis
    idpolitis over 11 years
    Thank you for your reply. I just have one task that will run a predefined number of times one after another. Do you think I still need to use semaphores? Also, if I create a new timer for each of the times the task runs, does it mean I need an array of timers or something of that sort?
  • m0skit0
    m0skit0 over 11 years
    You said you wanted to wait the first task to end. This needs a semaphore. You don't need to keep track of the timers if you don't want. They will be freed later automatically by the GC.