繁体   English   中英

Timer和timerTask小问题

[英]Timer and timerTask small issue

我是java的菜鸟。 这是我第一次在Java中使用timer和timerTask类。

我的应用程序的目的:

它是使用MySQL实现的多客户端应用程序。 我的应用程序是重复读取数据库数据。 如果数据库已更新,那么我也希望每个客户端的面板也都更新。 因此,我假设我需要一个计时器类,该类可以自动执行重复查询以读取我的数据库,然后在客户端的组件上进行一些更改。

问题:

我看起来以为是一些教程,并且我找到了这种方法。 由于this.updateTableStatus()方法在我的Table类中,因此如何在MyTimer(timerTask)类中使用该方法。

public class Table extends javax.swing.JFrame {

    public Table() {
        initComponents();
        MyTimer myTime = new MyTimer();

    }
    public void updateTableStatus(){
        // this is where I refresh my table status which is reading database data and make some change.
    }

    class MyTimer extends TimerTask{
        public MyTimer() {
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(this, new java.util.Date(), 1000);
        }
        public void run(){

            this.updateTableStatus();   // this is not working!!!, because they r not in the same class.  I need help to solve this problem.
        }
    }
}

帮帮我。 非常感谢。

最好使用Swing Worker ,然后在数据更改时发布结果。 这样,您在执行数据库查询时就不会阻止EDT。

如果要使用TimerTask,则需要将对TableModel的任何更新包装在SwingUtilities.invokeLater()中。

this.updateTableStatus(); 尝试引用MyTimer的updateTableStatus()方法(但没有这种方法)。 要引用Table的updateTableStatus()方法,可以将其更改为

Table.this.updateTableStatus();

注意
认真地说,我认为每秒从每个客户端检查数据库以查看是否有任何更改是非常糟糕的应用程序设计。 我建议您发布一个新问题,解释您当前的体系结构和要求,并询问有关如何有效监视数据库更改的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM