簡體   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