JavaFX periodic background task

后端 未结 5 964
时光说笑
时光说笑 2020-11-21 04:43

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

5条回答
  •  时光取名叫无心
    2020-11-21 05:15

    You can use Timeline for that matter:

    Timeline fiveSecondsWonder = new Timeline(
                     new KeyFrame(Duration.seconds(5), 
                     new EventHandler() {
    
        @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 background processes (which don't do anything to UI) you can use old good java.util.Timer:

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

提交回复
热议问题