JavaFX periodic background task

后端 未结 5 937
时光说笑
时光说笑 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:09

    Here is a solution using Java 8 and ReactFX. Say that you want to periodically recompute the value of Label.textProperty().

    Label label = ...;
    
    EventStreams.ticks(Duration.ofSeconds(5))          // emits periodic ticks
        .supplyCompletionStage(() -> getStatusAsync()) // starts a background task on each tick
        .await()                                       // emits task results, when ready
        .subscribe(label::setText);                    // performs label.setText() for each result
    
    CompletionStage getStatusAsync() {
        return CompletableFuture.supplyAsync(() -> getStatusFromNetwork());
    }
    
    String getStatusFromNetwork() {
        // ...
    }
    

    Compared to Sergey's solution, you don't dedicate the whole thread to getting status from the network, but instead use the shared thread pool for that.

提交回复
热议问题