JavaFX定期后台任务 [英] JavaFX periodic background task

查看:122
本文介绍了JavaFX定期后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试定期在JavaFX应用程序后台线程中运行,这会修改一些GUI属性.

I try to run in JavaFX application background thread periodically, which modifies some GUI property.

我想我知道如何使用javafx.concurrent中的TaskService类,并且不知道如何在不使用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
}

看起来很讨厌:(是否有更好的方法使用TaskService类来做到这一点?

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定期后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆