Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodic JavaFX Service

Tags:

java

javafx-2

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;
             }
         };
     }
 }
like image 928
BlueRebel Avatar asked Dec 25 '12 05:12

BlueRebel


People also ask

How do I add a delay in JavaFX?

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.

What is JavaFX platform runLater?

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.

Is JavaFX thread safe?

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.

Can a scene have multiple panes JavaFX?

The Scene it self can only have one root Pane. So if you want 2 panes in the Scene you need 3.


1 Answers

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.

like image 172
jewelsea Avatar answered Sep 21 '22 18:09

jewelsea