Java Reference
In-Depth Information
injected resource references a ManagedScheduledExecutorService that is identified by the name
concurrent/__defaultManagedScheduledExecutorService .
@Resource(name="concurrent/__defaultManagedScheduledExecutorService")
ManagedScheduledExecutorService mes;
To write the task that you wish to have scheduled, create a Java class that implements Runnable . As such, the class
will contain a run method, which will be invoked each time the scheduled task is initiated. The following example
demonstrates how to construct a task that can be used for logging. In this example, the Employee entity is queried on
a periodic basis to determine if new employees have been added to the database.
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.javaee7.entity.Employee;
/**
* Chapter 11 - Scheduled Logger
* @author Juneau
*/
public class ScheduledEmployeeAlert implements Runnable {
EntityManagerFactory emf = null;
EntityManager em = null;
@Override
public void run() {
emf = Persistence.createEntityManagerFactory("IntroToJavaEE7PU");
em = emf.createEntityManager();
queryEmployees();
}
public void queryEmployees(){
EntityTransaction entr = em.getTransaction();
entr.begin();
String qry = "select object(o) from Employee o";
Query query = em.createQuery(qry);
List<Employee> emps = query.getResultList();
for(Employee emp: emps){
// if employee is new then alert
}
}
}
To periodically invoke the task, utilize the ManagedScheduledExecutorService resource. The following JSF
managed bean class demonstrates how to invoke this type of service.
 
Search WWH ::




Custom Search