JavaFX 周期性后台任务 [英] JavaFX periodic background task
问题描述
我尝试定期在 JavaFX 应用程序后台线程中运行,这会修改一些 GUI 属性.
I try to run in JavaFX application background thread periodically, which modifies some GUI property.
我想我知道如何使用 javafx.concurrent
中的 Task
和 Service
类,但不知道如何运行这样的不使用 Thread#sleep()
方法的周期性任务.如果我可以使用 Executors
中的一些 Executor
制造方法(Executors.newSingleThreadScheduledExecutor()
)
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()
)
我尝试每 5 秒运行一次 Runnable
,这会重新启动 javafx.concurrent.Service
但它立即挂起 service.restart
甚至service.getState()
被调用.
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.
所以最后我使用 Executors.newSingleThreadScheduledExecutor()
,它每 5 秒触发一次我的 Runnable
并且 Runnable
运行另一个 Runnable
使用:
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
}
它看起来很糟糕:(有没有更好的方法来使用 Task
或 Service
类来做到这一点?
It looks very nasty :( Is there a better way to do this using Task
or Service
classes?
推荐答案
您可以为该任务使用时间轴:
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();
对于后台进程(对 UI 不做任何事情),您可以使用旧好的 java.util.Timer
:
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);
这篇关于JavaFX 周期性后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!