I am wanting to execute a task at a regular interval from my JavaFX application. The task pulls data from a remote stream.
While I know I could use a Timer as suggested below:
JavaFX periodic background task
I believe this should be able to be done using the JavaFX Service object. There's mention in the Javadoc about specifying a custom executor (ScheduledThreadPoolExecutor comes to mind here), but how would one specify the period and delay? Ideally, this would use the Service's usual start, reset, restart, and state bindings...
public class MyFirstLineService extends Service<String> {
private StringProperty url = new SimpleStringProperty(this, "url");
public final void setUrl(String value) { url.set(value); }
public final String getUrl() { return url.get(); }
public final StringProperty urlProperty() { return url; }
public MyFirstLineService() {
setExecutor(new ScheduledThreadPoolExecutor());
}
protected Task createTask() {
final String _url = getUrl();
return new Task<String>() {
protected String call() throws Exception {
URL u = new URL(_url);
BufferedReader in = new BufferedReader(
new InputStreamReader(u.openStream()));
String result = in.readLine();
in.close();
return result;
}
};
}
}
The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.
JavaFX contains the Platform class which has a runLater() method. The runLater() method takes a Runnable which is executed by the JavaFX application thread when it has time. From inside this Runnable you can modify the JavaFX scene graph.
The JavaFX scene graph, which represents the graphical user interface of a JavaFX application, is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread.
The Scene it self can only have one root Pane. So if you want 2 panes in the Scene you need 3.
A ScheduledService was requested in the JavaFX issue tracker - RT18702.
The tracker includes source for a preliminary implementation which has not been incorporated in the 2.2 branch. If needed, you could take a look at that source and see if it helps improve on your solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With