我尝试定期在JavaFX应用程序后台线程中运行,这会修改一些GUI属性.
I try to run in JavaFX application background thread periodically, which modifies some GUI property.
我想我知道如何使用javafx.concurrent中的Task和Service类,并且不知道如何在不使用Thread#sleep()方法的情况下运行此类定期任务.如果我可以使用Executors制作方法(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 matter:
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 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);更多推荐
JavaFX定期后台任务
发布评论