javafx

JavaFX periodic background task


I try to run in JavaFX application background thread periodically, which modifies some GUI property.

I think I know how to use Task and Service classes from javafx.concurrent and can't figure it out how to run such periodic task without using Thread#sleep() method. It would be nice if I can use some Executor from Executors fabricate methods (Executors.newSingleThreadScheduledExecutor())

I tried to run Runnable every 5 sec, which restarts javafx.concurrent.Service but it hangs immediately as service.restart or even service.getState() is called.

So finally I use Executors.newSingleThreadScheduledExecutor(), which fires my Runnable every 5 sec and that Runnable runs another Runnable using:

Platform.runLater(new Runnable() {
 //here i can modify GUI properties
}

It looks very nasty :( Is there a better way to do this using Task or Service classes?


Solution

  • You can use Timeline for that task:

    Timeline fiveSecondsWonder = new Timeline(
                     new KeyFrame(Duration.seconds(5), 
                     new EventHandler<ActionEvent>() {
    
        @Override
        public void handle(ActionEvent event) {
            System.out.println("this is called every 5 seconds on UI thread");
        }
    }));
    fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
    fiveSecondsWonder.play();
    

    for the background processes (which don't do anything to the UI) you can use old good java.util.Timer:

    new Timer().schedule(
        new TimerTask() {
    
            @Override
            public void run() {
                System.out.println("ping");
            }
        }, 0, 5000);