title: Java: Scheduling a task in random intervals
body: <p>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.</p>
  
  <p>I tried several things but nothing is working so far. My latest effort is below:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>"task" is a TimerTask. What I get is: </p>
  
  <pre><code>Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled
  </code></pre>
  
  <p>I understand from <a href="https://stackoverflow.com/questions/1041675/java-timer">here</a> 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.</p>
  
  <p>Any help will be really appreciated, thanks! </p>