用于从数据库接收数据的计时器

时间:2015-03-14 18:04:17

标签: java database timer

我将数据保存在变量中,需要每分钟更新一次。 代码如下所示:

public class PersonService {
    private static PersonDAO personDAO;
    private static List<Person> list;
    Timer timer;

    public PersonService() {
        personDAO = new PersonDAO();
        list = personDAO.getList();
        final List<Person> finalList;
        timer = new Timer();
        timer.schedule(new TimerTask() {
                           @Override
                           public void run() {
                               list = personDAO.getList();
                               System.err.println("RENEW");
                           }
                       },
                60000, 60000);
    }

    public List<Person> getList() {
        return list;
    }
}

public class PersonDAO {
    private Logger LOGGER = Logger.getLogger(PersonDAO.class);

    public List<Person> getList() {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();

        SQLQuery query = session.createSQLQuery("select * from Person");
        query.addEntity(Person.class);
        List<Person> list = query.list();

        session.close();
        sessionFactory.close();

        return list;
    }
}

所以我试图创建每分钟更新变量的计时器,但会出现这样的异常:

Exception in thread "Timer-0" org.hibernate.service.UnknownServiceException:             Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:201)
at org.hibernate.internal.AbstractSessionImpl.getJdbcConnectionAccess(AbstractSessionImpl.java:341)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.<init>(JdbcCoordinatorImpl.java:114)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.<init>(TransactionCoordinatorImpl.java:89)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:258)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1589)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:999)
at com.fujitsu.homework.dao.PersonDAO.getList(PersonDAO.java:18)
at com.fujitsu.homework.service.PersonService$1.run(PersonService.java:27)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

可能有一些我不明白的东西。 有没有办法做这些事情?

0 个答案:

没有答案