1

Let's say I have a custom TimerTask doing stuff.

So normally a timer task would look something like this:

public class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        // Do work...
    }
}

And I schedule it for a continuous repeating cycle via a Timer to execute every 10 seconds.

Timer myTimer = new Timer();
MyTimerTask myTask = new MyTimerTask();
myTimer.schedule(myTask,0,10000);

Under normal conditions this works just fine, but since I perform some GUI update operations in this task I have to call the Runnable from the JavaFX application thread.

In essence this means that I have to call the Platform.runLater on the Runnable (MyTimerTask) when I want to run it.

But since I don't explicitly call the run() on the task since I put it on the TaskQueue via Timer.schedule, I have to resort to changing MyTimerTask to something like this:

public class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        Platform.runLater(
            new Runnable() {
                public void run() {
                    //Do work...
                }
            }
        );
    }
}

Which feels like a very crude way to do this.

So I was wondering if there is a better way to do this?

Ceiling Gecko
  • 3,104
  • 2
  • 24
  • 33
  • This is pretty similar (almost a duplicate) to: [JavaFX periodic background task](http://stackoverflow.com/questions/9966136/javafx-periodic-background-task) – jewelsea Jun 02 '15 at 09:00

1 Answers1

1

JavaFX has the animation package that can also be used for updating the UI at regular intervals.

Take a look at the class Timeline :

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(10),
        new EventHandler<ActionEvent>() {
            public void handle(ActionEvent ae) {
                 // do stuff
            }
        }
));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

The timeline will be executed automatically in the JavaFX thread.

Dainesch
  • 1,320
  • 13
  • 19