我每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();。我怎样才能做到这一点?

最佳答案

首先将当前对象存储到变量中,然后使用.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);
    }

10-04 22:06
查看更多