My Java EE app should have a background thread, which updates DB state. I'd like to use JPA for this purpose. What are the best practices to do it? (Our EE container is prior JSR-236, so ManagedExecutorService is not our choice)
By the way I tried the code bellow, but it didnt work - no exception was thrown, but nothing was saved into DB. Without background thread and using injected EntityManager everything saved:
@Singleton
public class IdentityDao{
@PersistenceUnit(unitName = "routing")
private EntityManagerFactory emf;
@Resource
private UserTransaction utx;
@PostConstruct
protected void startConverter() {
new Converter();
}
private class Converter implements Runnable {
private Converter() {
ScheduledExecutorService scheduler = ThreadUtils.newSingleThreadScheduledExecutor("test", true);
scheduler.scheduleAtFixedRate(this, 5, 5, TimeUnit.SECONDS);
}
@Override
public void run() {
EntityManager em = emf.createEntityManager();
try {
utx.begin();
em.persist(new PersonEntity("123"));
utx.commit();
} catch (Exception e) {
try {
e.printStackTrace();
utx.rollback();
} catch (Exception exc) {
}
} finally {
em.close();
}
}
}
}