mynameisJEFF
mynameisJEFF

Reputation: 4239

javafx: How to set ScheduledService to restart itself on a random time interval?

I have a ScheduledService that restarts at a random time (from 1 to 101 seconds) by setting that setPeriod(Duration.seconds((int) 1 + Math.rand()*100)). If the random number is 65, the service systematically restarts every 65 seconds.

However, what I really want is that it will restart at a random (not fixed) time on each cycle.

UPDATE: By random , I mean it will generate a random number for each run. So, maybe the service will restart again next 10 seconds, next time 100 seconds, next time 35 seconds.

How can I achieve this ?

class Foo

    private final ScheduledService<Item> service = new ScheduledService<Item>() {
        @Override
        public Task<Item> createTask(){
            return new Task<Item>() {
                @Override
                public Item call() throws Exception {       
                    return //Item object
                }
            };
        }
    };

    // constructor
    public Foo(){
           service.setPeriod(Duration.seconds((int) 1 + Math.rand()*100));
           ....
           service.startMonitoring();
    }


    public final void startMonitoring() {
        service.restart();
    }

    public final void stopMonitoring() {
        service.cancel();
    }
}

Upvotes: 3

Views: 638

Answers (1)

ItachiUchiha
ItachiUchiha

Reputation: 36742

You can change it on the completion of the present running Service.

From the Docs :

If the period or delay is changed while the ScheduledService is running, the new values will be taken into account on the next iteration.

service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
     @Override
     public void handle(WorkerStateEvent t) {
          service.setPeriod(Duration.seconds(1 + Math.random()*100));
     }
});

Upvotes: 4

Related Questions