Timers and javafx Timers and javafx multithreading multithreading

Timers and javafx


You don't need java.util.Timer or java.util.concurrent.ScheduledExecutorService to schedule future actions on the JavaFX application thread. You can use JavaFX Timeline as a timer:

new Timeline(new KeyFrame(        Duration.millis(2500),        ae -> doSomething()))    .play();

Alternatively, you can use a convenience method from ReactFX:

FxTimer.runLater(        Duration.ofMillis(2500),        () -> doSomething());

Note that you don't need to wrap the action in Platform.runLater, because it is already executed on the JavaFX application thread.


If you touch any JavaFX component you must do so from the Platform thread (which is essentially the event dispatch thread for JavaFX.) You do this easily by calling Platform.runLater(). So, for instance, it's perfectly safe to do this:

new Thread() {    public void run() {        //Do some stuff in another thread        Platform.runLater(new Runnable() {            public void run() {                label.update();                javafxcomponent.doSomething();            }        });    }}.start();


berry120 answer works with java.util.Timer too so you can do

Timer timer = new java.util.Timer();timer.schedule(new TimerTask() {    public void run() {         Platform.runLater(new Runnable() {            public void run() {                label.update();                javafxcomponent.doSomething();            }        });    }}, delay, period);

I used this and it works perfectly