10 Replies Latest reply on Jul 21, 2011 12:10 PM by JEE 4 Hire

    null entityManager in Quartz job

    Shane Sarver Newbie
      When the QuartzInitializer starts, the entityManager is not null.
      When the HelloJob executes, the entityManager is null.
      Also, the instance of org.jboss.logging.Logger does not work inside HelloJob.
      How can I get a valid handle to entityManager inside HelloJob?
      Why exactly is it failing?  Is it because the job is retrieved from the database when it is run
      by the quartz scheduler?   In Seam 2, using  @In EntityManager entityManager worked.


      @Singleton
      @Startup
      public class QuartzInitializer {
        @PersistenceContext
        private EntityManager entityManager;
        @Inject
        private Logger log;

        public QuartzInitializer() {
        }

        @PostConstruct
        public void init() throws Exception {
          startScheduler();
          createJob();
        }

        public void startScheduler() throws Exception {
          InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("seam.quartz.properties");
          StdSchedulerFactory sf = new StdSchedulerFactory();
          sf.initialize(is);
          sched = sf.getScheduler();
          sched.start();
        }

        public void createJob() throws Exception {
          SchedulerFactory sf = new StdSchedulerFactory();
          Scheduler scheduler = sf.getScheduler("QuartzScheduler00");
          Date runTime = evenMinuteDate(new Date());
          // define the job and tie it to our HelloJob class
          JobDetail job = newJob(HelloJob.class)
              .withIdentity("job1", "group1")
              .build();
          // Trigger the job to run on the next round minute
          Trigger trigger = newTrigger()
              .withIdentity("trigger1", "group1")
              .startAt(runTime)
              .build();
          // Tell quartz to schedule the job using our trigger
          scheduler.scheduleJob(job, trigger);
          log.info(job.getKey() + " will run at: " + runTime);
        }
      }
      ####################################################
      public class HelloJob implements Job {
        @Inject
        private Logger log;
        @PersistenceContext
        private EntityManager entityManager;

        public HelloJob() {
        }

        public void execute(JobExecutionContext context) throws JobExecutionException {
          try {
            System.out.println("***Hello World! job: " + context.getJobDetail().getKey() + " executed at " + new Date());
            // Reschedule job to run a minute later
            Scheduler scheduler = context.getScheduler();
            Trigger t = context.getTrigger();
            SimpleTriggerImpl timpl = (SimpleTriggerImpl)t;
            Date runTime = evenMinuteDate(new Date());
            timpl.setNextFireTime(runTime);
            Trigger trigger = newTrigger()
              .withIdentity("trigger999", "group1")
              .startAt(runTime)
              .build();
            scheduler.rescheduleJob(t.getKey(), trigger);
          }
          catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      #########################################################
      # seam.quartz.properties
      org.quartz.scheduler.instanceName = QuartzScheduler00
      org.quartz.scheduler.instanceId = AUTO
      org.quartz.scheduler.rmi.export = false
      org.quartz.scheduler.rmi.proxy = false
      org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
      org.quartz.threadPool.threadCount = 5
      org.quartz.threadPool.threadPriority = 5
      org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
      org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
      org.quartz.jobStore.tablePrefix = QRTZ_
      org.quartz.jobStore.isClustered = false
      org.quartz.jobStore.dataSource = QUARTZ
      org.quartz.dataSource.QUARTZ.driver = com.mysql.jdbc.Driver
      org.quartz.dataSource.QUARTZ.URL = jdbc:mysql://localhost:3306/quartz
      org.quartz.dataSource.QUARTZ.user = XXXXXXXXXX
      org.quartz.dataSource.QUARTZ.password = XXXXXXXXXX
      org.quartz.dataSource.QUARTZ.maxConnections = 5



        • 1. Re: null entityManager in Quartz job
          Shane Sarver Newbie

          jars used:



             83294  Defl:N    68416  18% 2011-07-18 16:01 9869bd05  WEB-INF/lib/seam-servlet-3.0.1-20110705.041111-5.jar
            204093  Defl:N   181695  11% 2011-07-07 12:54 ed9a2ff2  WEB-INF/lib/picketlink-idm-core-1.5.0.Alpha02.jar
             55966  Defl:N    44907  20% 2011-07-07 12:54 d81b0cc2  WEB-INF/lib/seam-international-3.0.0.Final.jar
            529064  Defl:N   490198   7% 2011-07-18 14:13 cb9a1aec  WEB-INF/lib/quartz-2.0.1.jar
            445288  Defl:N   421452   5% 2011-07-12 15:16 3684c6c5  WEB-INF/lib/antlr-2.7.7.jar
          1627515  Defl:N  1470306  10% 2011-07-07 12:54 e71d8ef4  WEB-INF/lib/primefaces-3.0.M2.jar
            543011  Defl:N   456324  16% 2011-07-12 14:02 f915bdef  WEB-INF/lib/joda-time-1.6.1.jar
            153633  Defl:N   139858   9% 2011-07-18 08:58 267a0105  WEB-INF/lib/seam-security-impl-3.0.1-20110624.041853-12.jar
          1567356  Defl:N  1418671  10% 2011-07-18 08:58 a2492dac  WEB-INF/lib/richfaces-components-ui-4.1.0-20110718.130748-64.jar
            161455  Defl:N   122304  24% 2011-07-12 15:10 55c0bc93  WEB-INF/lib/knowledge-api-5.2.0.Final.jar
          1902276  Defl:N  1719856  10% 2011-07-12 15:10 91eaa4f6  WEB-INF/lib/drools-core-5.2.0.Final.jar
            136473  Defl:N   115134  16% 2011-07-18 08:58 a3cdeabd  WEB-INF/lib/richfaces-core-api-4.1.0-20110718.130115-62.jar
             15071  Defl:N    12479  17% 2011-04-04 11:31 a1e02acb  WEB-INF/lib/jta-1.1.jar
             85247  Defl:N    64105  25% 2011-07-18 08:58 70fc0fb5  WEB-INF/lib/richfaces-components-api-4.1.0-20110718.130748-64.jar
            897071  Defl:N   858346   4% 2011-07-12 15:16 a1635c95  WEB-INF/lib/antlr-3.3.jar
          1674737  Defl:N  1601274   4% 2011-07-07 12:55 b5de0b5f  WEB-INF/lib/ecj-3.5.1.jar
              9753  Defl:N     8262  15% 2011-07-19 08:04 077eb18d  WEB-INF/lib/slf4j-log4j12-1.6.1.jar
             15808  Defl:N    12066  24% 2011-07-07 12:54 cbb7cd31  WEB-INF/lib/sac-1.3.jar
             91494  Defl:N    81063  11% 2011-07-18 08:58 297819e6  WEB-INF/lib/seam-config-xml-3.0.1-20110511.043145-7.jar
            269014  Defl:N   245020   9% 2011-06-20 14:42 0d19c92a  WEB-INF/lib/commons-net-3.0.1.jar
            787920  Defl:N   754098   4% 2011-07-18 16:27 68512c76  WEB-INF/lib/mysql-connector-java-5.1.17.jar
              7457  Defl:N     5972  20% 2011-07-18 14:13 cdac3310  WEB-INF/lib/quartz-jboss-2.0.1.jar
            481535  Defl:N   435562  10% 2011-07-19 08:04 39fbbb94  WEB-INF/lib/log4j-1.2.16.jar
            713433  Defl:N   657365   8% 2011-07-12 15:10 3e88a598  WEB-INF/lib/mvel2-2.1.0.drools2.jar
            253950  Defl:N   241386   5% 2011-05-12 11:27 f758d70e  WEB-INF/lib/cssparser-0.9.5.jar
          1114265  Defl:N   987976  11% 2011-05-12 11:27 57d773f1  WEB-INF/lib/guava-r08.jar
             25496  Defl:N    22183  13% 2011-07-14 12:55 1a95d60b  WEB-INF/lib/slf4j-api-1.6.1.jar
            119223  Defl:N   103690  13% 2011-07-18 08:58 fb1581b3  WEB-INF/lib/seam-persistence-3.0.1-20110711.040751-17.jar
            148627  Defl:N   138829   7% 2011-07-12 15:16 3e8b388d  WEB-INF/lib/stringtemplate-3.2.1.jar
            397907  Defl:N   343667  14% 2011-07-07 12:54 7f34b227  WEB-INF/lib/seam-solder-3.0.0.Final.jar
            988489  Defl:N   902079   9% 2011-07-12 15:16 22c8db9d  WEB-INF/lib/drools-compiler-5.2.0.Final.jar
             33716  Defl:N    23689  30% 2011-07-18 08:58 3a591eab  WEB-INF/lib/seam-security-api-3.0.1-20110624.041806-12.jar
            163650  Defl:N   149460   9% 2011-07-12 15:16 e8acd98f  WEB-INF/lib/antlr-runtime-3.3.jar
            608376  Defl:N   554163   9% 2011-07-14 12:55 4bb8e85b  WEB-INF/lib/c3p0-0.9.1.1.jar
            415822  Defl:N   384150   8% 2011-07-18 08:58 8c572ac0  WEB-INF/lib/richfaces-core-impl-4.1.0-20110718.130115-61.jar
             23055  Defl:N    14694  36% 2011-07-07 12:54 5dfcdff2  WEB-INF/lib/picketlink-idm-spi-1.5.0.Alpha02.jar
             27714  Defl:N    18846  32% 2011-07-07 12:54 9718b1ca  WEB-INF/lib/picketlink-idm-api-1.5.0.Alpha02.jar
             25717  Defl:N    20670  20% 2011-07-07 12:54 8473b909  WEB-INF/lib/picketlink-idm-common-1.5.0.Alpha02.jar

          • 2. Re: null entityManager in Quartz job
            Jason Porter Master

            Couple of things wrong I see with this.


            1. Don't use @PersistenceContext, you should be injecting it unless you want to use EE6 to manage it, in which case, yes your EntityManager will be null when CDI calls it.
            2. You aren't running in a conversation context in Cron, so it may not work exactly right now anyway.

            • 3. Re: null entityManager in Quartz job
              JEE 4 Hire Newbie
              Using @Inject does not work.
              I added a method to query the database for the number of jobs to show the failure.
              Using @PersistenceContext did provide a valid handle to entityManager in the QuartzInitializer.
              I also changed from @Singleton @Startup --> @Alternative
              How can I get a valid handle to the entityManager in HelloJob?


              import javax.enterprise.inject.Alternative;
              import javax.inject.Inject;

              @Alternative
              public class QuartzInitializer {
                //@PersistenceContext
                @Inject
                private EntityManager entityManager;
                @Inject
                private Logger log;
                private Scheduler sched;

                public QuartzInitializer() {
                }

                public void init(@Observes @Initialized WebApplication webapp) {
                  startScheduler();
                  createJob();
                  queryJobCount()
                }

                public void startScheduler() throws Exception {
                  InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("seam.quartz.properties");
                  StdSchedulerFactory sf = new StdSchedulerFactory();
                  sf.initialize(is);
                  sched = sf.getScheduler();
                  sched.start();
                }

                public void createJob() throws Exception {
                  SchedulerFactory sf = new StdSchedulerFactory();
                  Scheduler scheduler = sf.getScheduler("QuartzScheduler00");
                  Date runTime = evenMinuteDate(new Date());
                  // define the job and tie it to our HelloJob class
                  JobDetail job = newJob(HelloJob.class)
                      .withIdentity("job1", "group1")
                      .build();
                  // Trigger the job to run on the next round minute
                  Trigger trigger = newTrigger()
                      .withIdentity("trigger1", "group1")
                      .startAt(runTime)
                      .build();
                  // Tell quartz to schedule the job using our trigger
                  scheduler.scheduleJob(job, trigger);
                  log.info(job.getKey() + " will run at: " + runTime); 
                }

                public void queryJobCount() throws Exception {
                  List<Job> list = entityManager.createQuery("select j from Job j").getResultList();
                  log.info("queryJobCount(): " + list.size());
                }
              }
              ###############################################################
              public class EntityManagerProducer {
                 @Produces
                 @ExtensionManaged
                 @ConversationScoped
                 @PersistenceUnit
                 EntityManagerFactory emf;
              }
              ################################################################
              org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.ConversationScoped
                      at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:667) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:77) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:124) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.proxies.EntityManager$ManagedPersistenceContext$2106413589$Proxy$_$$_WeldClientProxy.createQuery(EntityManager$ManagedPersistenceContext$2106413589$Proxy$_$$_WeldClientProxy.java) [weld-core-1.1.2.AS7.jar:]
                      at QuartzInitializer.queryJobCount(QuartzInitializer.java:211) [classes:]
                      at QuartzInitializer.startScheduler(QuartzInitializer.java:132) [classes:]
                      at QuartzInitializer.init(QuartzInitializer.java:74) [classes:]
                      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_26]
                      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_26]
                      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_26]
                      at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_26]
                      at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:305) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:299) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:188) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:59) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:198) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:282) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:265) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:234) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.manager.BeanManagerImpl.notifyObservers(BeanManagerImpl.java:635) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.manager.BeanManagerImpl.fireEvent(BeanManagerImpl.java:622) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.weld.manager.BeanManagerImpl.fireEvent(BeanManagerImpl.java:616) [weld-core-1.1.2.AS7.jar:2011-07-06 12:26]
                      at org.jboss.seam.servlet.event.AbstractServletEventBridge.fireEvent(AbstractServletEventBridge.java:45) [seam-servlet-3.0.1-20110720.040801-6.jar:]
                      at org.jboss.seam.servlet.event.ServletEventBridgeListener.contextInitialized(ServletEventBridgeListener.java:62) [seam-servlet-3.0.1-20110720.040801-6.jar:]
                      at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3368) [jbossweb-7.0.0.CR4.jar:7.0.0.Final]
                      at org.apache.catalina.core.StandardContext.start(StandardContext.java:3821) [jbossweb-7.0.0.CR4.jar:7.0.0.Final]
                      at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:70) [jboss-as-web-7.0.0.Final.jar:7.0.0.Final]
                      at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1765)
                      at org.jboss.msc.service.ServiceControllerImpl$ClearTCCLTask.run(ServiceControllerImpl.java:2291)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_26]
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_26]
                      at java.lang.Thread.run(Thread.java:662) [:1.6.0_26]
              • 4. Re: null entityManager in Quartz job
                JEE 4 Hire Newbie

                I am not using Seam Cron, because I want to reschedule the job.

                • 7. Re: null entityManager in Quartz job
                  Jason Porter Master

                  Thanks for creating the issue.

                  • 8. Re: null entityManager in Quartz job
                    JEE 4 Hire Newbie

                    Why is the log handle null when I inject it into a quartz job?
                    How can I get a valid handle to the log?

                    • 9. Re: null entityManager in Quartz job
                      Sebastian Sachtleben Novice

                      You should check out the code of Seam Cron. The persistence context injection works fine in my cron jobs running with Seam Cron.

                      • 10. Re: null entityManager in Quartz job
                        JEE 4 Hire Newbie

                        What source code files contain persistence code injection?
                        Seam Cron looks like a very nice API to have a job run periodically, for example to check your email inbox every t seconds for new mail.
                        I see there are annotations to hard code a fixed constant periodic interval in the method parameter list.


                        I want to schedule a job to run non-periodically:
                        0) Start the Quartz scheduler.
                        1) Schedule a new job to start at an arbitrary start time.
                        2) When the job runs, use the entityManager in the job to read/write objects from/to the database to determine next time to run job.
                        3) Reschedule the job by modifying the associated Quartz trigger with the determined next time to run.

                        I would like to have maximum flexibility in job scheduling.
                        Is there some way I can utilize Seam Cron to accomplish this?