Reputation:
I have one problem. I am creating JavaFX application for desktop. I have thread in my app that runs in background, let's assume that it is downloading files from the internet.
I have read articles about concurrency in JavaFX. There is special class Task. I have extended my class with Task. But it can only return some value and after that it will shut down.
But I need to have this task running during all app lifetime, and when , for instance file is downloaded, it should post result to the UI thread, to be more precise on controller which in turn update some ui component.
I know that Task has updateProgress method, maybe I can bind it not only to receive integers, but complex Objects.
Or there is other good approach to follow in my case.
Please help with this problem.
Upvotes: 4
Views: 1270
Reputation: 36742
JavaFX provides you with ScheduledService which can be scheduled for repetitive works. The javadoc says,
The ScheduledService is a Service which will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure.
A very simple example would be :
ScheduledService<Object> service = new ScheduledService<Object>() {
protected Task<Object> createTask() {
return new Task<Object>() {
protected Object call() {
// Connect to a Server
// Download the object
updateProgress(...);
return object; // Useful in case you want to return data, else null
}
};
}
};
service.setPeriod(Duration.seconds(10)); //Runs every 10 seconds
//bind the service progress/message properties
progressBar.progressProperty().bind(service.progressProperty());
There are non-javafx ways to achieve this as well, you can use :
Upvotes: 2
Reputation: 34508
The easiest way here would be to use plain old Thread:
// create new thread at start, e.g. at the end for Application.start() method
new Thread(new Runnable() {
public void run() {
while(true) {
//load my data
// once loaded
// update UI using
Platform.runLater(new Runnable() {
public void run() {
// here goes my update on FX UI thread
}
});
// update is done let's look for more data
}
}
}).start();
Upvotes: 1