Hello Everyone, I’ve been trying to generate a random int to execute a class file AutomatedLightningTimer() by a random amount of seconds (10 -1), but the random int generator executes only once and executes the AutomatedLightningTimer() class by the same amount of seconds. Is there a way to continue to execute the randomInt() so that the AutomatedLightningTimer() class executes at a random second (1 -10)?Thanks!
@Listener
public void postInit (GamePostInitializationEvent event){
//Automated Lightning Striker
Scheduler scheduler = Sponge.getScheduler();
Task.Builder taskBuilder = scheduler.createTaskBuilder();
Task task = taskBuilder.execute(new AutomatedLightningTimer())
.interval(RandomInt.randomInt(), TimeUnit.SECONDS).submit(this);
}
public class RandomInt {
public static long randomInt() {
int random = new Random().nextInt(10);
return random;
}
}
What I would do is instead of running a repeating task, create a run once task that executes AutomatedLightningTimer and inside AutomatedLightningTimer create a new delayed task after finishing whatever logic that also executes AutomatedLightningTimer, essentially creating a loop, but giving you the opportunity to set a new random interval between executions
@Listener
public void postInit (GamePostInitializationEvent event){
Sponge.getScheduler().createTaskBuilder().execute(new AutomatedLightningTimer()).submit(this);
}
public class AutomatedLightningTimer implements Consumer<Task> {
@Override
public void accept(Task t) {
// DO FUN STUFF
// DO MORE FUN STUFF
Sponge.getScheduler().createTaskBuilder().execute(new AutomatedLightningTimer()).delay(ThreadLocalRandom.current().nextInt(10), TimeUnit.SECONDS).submit(YOUR MAIN CLASS);
}
}
1 Like
Thanks! The code you provided is definitely a lot cleaner than what I had in mind.
Actually to clean it more replace
Sponge.getScheduler().createTaskBuilder()
With this
Task.builder()
1 Like
and replace a separate class with a method and a :: ref, or the whole thing with a lambda
2 Likes