如何在java Timer中只显示一次窗口

时间:2016-03-23 20:07:54

标签: java javafx

我的应用中有一个Timer。 Timer每10秒连接和断开数据库。这只是为了知道我的数据库何时无法解决。也许还有其他方法。但我这样做了。 如何显示警报窗口一次成功连接并重复跳闸? 谢谢你的任何帮助!

Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            Platform.runLater(new Runnable() {
                public void run() {
                    SqlTransport.openConnectionToDB();
                    System.out.println("connect");
                    if (SqlTransport.openConnectionToDB() == false) {
                        alertWindow.display();
                        caseCount.setVisible(false);
                        System.out.println("noConnection");
                    }else {
                    System.out.println("connectDone");
                    caseCount.setVisible(true);
                        caseCount.setText(String.valueOf(SqlTransport.getOpenedCount()));
                        pause.playFromStart();
                        pause.setOnFinished(e -> {
                            SqlTransport.closeConnectionToDB();
                            System.out.println("closeDone");
                        });
                    }
                }
            });
        }
    }, 10000, 10000);

1 个答案:

答案 0 :(得分:0)

TimerTask添加一个布尔字段,指示上次检查连接是否有效。每次运行任务时都适当地设置字段。仅在上次连接时显示窗口。

编辑:这是一些代码,试一试。

Timer timer = new Timer();
timer.schedule(new TimerTask() {

    // It's possible that a starting value of false will
    // match your desired behaviour better.
    // Experiment with a situation where there is no connection initially.
    boolean previouslyConnected = true;

    public void run() {
        Platform.runLater(new Runnable() {
            public void run() {
                SqlTransport.openConnectionToDB();
                System.out.println("connect");
                boolean connected = SqlTransport.openConnectionToDB();
                // ! means 'not'. This is typically written instead of 'connected == false'
                if (!connected) {
                    if (previouslyConnected) {
                        alertWindow.display();
                    }
                    caseCount.setVisible(false);
                    System.out.println("noConnection");
                } else {
                    System.out.println("connectDone");
                    caseCount.setVisible(true);
                    caseCount.setText(String.valueOf(SqlTransport.getOpenedCount()));
                    pause.playFromStart();
                    pause.setOnFinished(e -> {
                        SqlTransport.closeConnectionToDB();
                        System.out.println("closeDone");
                    });
                }
                previouslyConnected = connected;
            }
        });
    }
}, 10000, 10000);