I have a working JSF application with JPA. The JTA-DataSource is wildfly-managed.
Now I have to run some database operations periodically. As mentioned here ( SO: How to run a background task in a servlet based web application? ) I created the two classes:
@WebListener
public class Scheduler implements ServletContextListener {
private ScheduledExecutorService scheduler;
@SuppressWarnings("deprecation")
@Override
public void contextInitialized(ServletContextEvent event) {
Calendar c = new GregorianCalendar();
Date d = c.getTime();
int stm = 60 - d.getSeconds();
int mth = 60 - d.getMinutes();
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new TestRunner(), stm, 60, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
public class TestRunner implements Runnable {
private EntityManager em;
public TestRunner() {
}
@Override
public void run() {
this.Test();
}
public void Test() {
System.out.println("Test executed...");
if (this.em != null) {
System.out.println(em.find(Ship.class, 2).getName());
System.out.println(em.find(Commodity.class, 1).getName());
} else {
System.out.println("EntityManager is null");
}
}
}
The best whould be to access the registered Persistence Unit.
I tried to get the EM via @PersistenceContext(unitName = "PU")
, tried to register the Persistence in the web.xml to get it via JNDI, but had no luck.
Where is my mistake?