如何使用Java从MySQL获取实时数据

问题描述 投票:0回答:1

我每2秒设置了一个调度程序:

private static EntityManagerFactory entityManagerFactory =
              Persistence.createEntityManagerFactory("onezero");
public static void main( String[] args )
{ 
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
            public void run() {
                System.out.println("Hello World");
                try {
                long start = System.currentTimeMillis();
                //System.out.println( "Hello World!" );
                SearchEURUSD(); 
            }
            catch (Exception e) {
                System.out.print(e);
            }
        }       
    }, 0, 2000);
}

否,我希望将此更改为数据库中的实时检查。如果我的数据库发生任何更改,我希望调用SearchEURUSD();。我该怎么办?

java mysql real-time real-time-data
1个回答
0
投票

最初将当前对象存储到变量中,然后使用。equals()方法进行比较。完整的示例代码:

private static EntityManagerFactory entityManagerFactory =
              Persistence.createEntityManagerFactory("onezero");
    public static void main( String[] args )
    { 
        //Object is your model class
        Object currentObject=null;

        Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {
           System.out.println("Hello World");
        try{
            long start = System.currentTimeMillis();
        //System.out.println( "Hello World!" );
            // initialize dbObject with the object you got from db.
            Object dbObject=objectGotFromDb;
            if(currentObject==null){
             currentObject=dbObject;
            }
            if(!currentObject.equal(dbObject){
            //Current object and db object are not equal
            SearchEURUSD(); 
            //updating the current object with updated db object.
            currentObject=dbObject;
            }
    }catch (Exception e){
        System.out.print(e);
    }
        }       
    }, 0, 2000);
    }
© www.soinside.com 2019 - 2024. All rights reserved.