JavaFX定期后台任务

编程入门 行业动态 更新时间:2024-10-23 03:19:17
本文介绍了JavaFX定期后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试定期在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定期后台任务

本文发布于:2023-11-15 05:45:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   JavaFX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!