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