+-

我有一个ScheduledService,它通过设置setPeriod(Duration.seconds((int)1 Math.rand()* 100))在随机时间(从1到101秒)重新启动.如果随机数是65,则该服务每65秒系统地重新启动一次.
但是,我真正想要的是它将在每个周期的随机(不固定)时间重新启动.
更新:通过random,我的意思是它将为每次运行生成一个随机数.因此,服务可能会在下一个10秒,下一个100秒,下一个35秒再次重新启动.
我该如何实现?
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();
}
}
最佳答案
您可以在当前运行的服务完成时进行更改.
从文档中:
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));
}
});
点击查看更多相关文章
转载注明原文:javafx:如何设置ScheduledService在随机时间间隔内自行重启? - 乐贴网