I'm already familiar with repeating tasks every n seconds by using Java.util.Timer and Java.util.TimerTask. But lets say I want to print "Hello World" to the console every random seconds from 1-5. Unfortunately I'm in a bit of a rush and don't have any code to show so far. Any help would be apriciated.
3 Answers
Let's do it in 2 steps:
static Timer timer = new Timer();
static class TimTask extends TimerTask {
public void run() {
int delay = (1 + new Random().nextInt(4)) * 1000;
timer.schedule(new TimTask(), delay);
System.out.println("Hello world..!");
}
}
public static void main(String[] args) throws Exception {
new TimTask().run();
}
This can be a good way to start...
Random r = new Random();
while(...){
printHelloWorld();
//calculate a random int between 1 and 5 and multiply for 1000
Thread.sleep(r);
}
Here is an example. But if you can't use Java 8 you have to replace the lambda expression with an anonymous class.
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class Time {
final static Random rand = new Random();
private static void _repeatRandom(Timer timer, long min, long max, int count, Runnable r) {
if(count < 1) {
timer.cancel();
return;
}
long delay = (long)(rand.nextDouble() * (max - min)) + min;
timer.schedule(new TimerTask() {
public void run() {
r.run();
_repeatRandom(timer, min, max, count - 1, r);
}
}, delay);
}
static void repeatRandom(long min, long max, int count, Runnable r) {
Timer timer = new Timer();
_repeatRandom(timer, min, max, count, r);
}
public static void main(String[] args) {
repeatRandom(1000, 5000, 10, () -> System.out.println("Hello World"));
}
}
This code prints "Hello World" 10 times and waits between 1 and 5 seconds each time.
"Hello World"
to the console every random seconds. What's the question?