Search code examples
quartz-schedulerejb-3.1stateful-session-bean

How to access EJB from a Quartz Job


Well, I'm using Quartz to schedule some jobs that I need in my application. But, I need some way to access a Stateful SessionBean on my Job. I knew that I can't inject it with @EJB. Can anyone help me? Thanks.


Solution

  • I used the EJB3InvokerJob to invoke the methods of my EJB. Then I created my jobs that extends the EJB3InvokerJob, put the parameters of what EJB and method it should call and then call the super.execute().

    The EJB3InvokerJob can be found here: http://jira.opensymphony.com/secure/attachment/13356/EJB3InvokerJob.java

    My Job is looking like this:

    public class BuscaSistecJob extends EJB3InvokerJob implements Job{
    
        private final Logger logger = Logger.getLogger(this.getClass());
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
        dataMap.put(EJB_JNDI_NAME_KEY, "java:app/JobService");
        dataMap.put(EJB_INTERFACE_NAME_KEY, "br.org.cni.pronatec.controller.service.JobServiceLocal");
        dataMap.put(EJB_METHOD_KEY, "buscaSistec");
        Object[] arguments = new Object[1];
        arguments[0] = jobExecutionContext.getTrigger().getStartTime();
        dataMap.put(EJB_ARGS_KEY, arguments);
        Class[] argumentTypes = new Class[1];
        argumentTypes[0] = Date.class;
        dataMap.put(EJB_ARG_TYPES_KEY, argumentTypes);
    
        super.execute(jobExecutionContext);
        }
    
    }
    

    And my EJB is like this:

    @Stateless
    @EJB(name="java:app/JobService", beanInterface=JobServiceLocal.class)
    public class JobService implements JobServiceLocal {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Resource
        private UserTransaction userTransaction;
    
        @Override
        public void buscaSistec(Date dataAgendamento) {
        // Do something
        }
    

    I expect to help someone.