4 Replies Latest reply on Jul 18, 2012 11:06 PM by Lukas Camra

    Seam Managed Persistence Context doesn't work with @Schedule

    Lukas Camra Newbie

      This might be helpful to someone. I'm using JBoss 7.1.1 Final with Weld, Seam 3.1. I wanted to use @Schedule annotation to process some tasks at certain time. When the task is being processed, it needs to pick up some data from database using entity manager. However, since I'm using seam managed persistence context and the method annotated by @Schedule is not called from JSF, it doesn't work. I get

      WELD-001303 No active contexts for scope type javax.enterprise.context.ConversationScoped

      First option how to solve this problem is to inject standard entity manager. This works, however since the business logic behind is shared by task system and all other components, it turns out that it's difficult. So I googled possible solutions and here: http://comments.gmane.org/gmane.comp.java.cdi.seam.devel/2003 , I found a workaround:

       

         private void initConversationContext() {
              conversationContext = Container.instance().deploymentManager().instance().select(BoundConversationContext.class).get();
              request = new MutableBoundRequest(new HashMap<String, Object>(), new HashMap<String, Object>());
              conversationContext.associate(request);
              conversationContext.activate();
          }
      
          private void cleanupConversationContext() {
              if(conversationContext != null && conversationContext.isActive()) {
                  conversationContext.deactivate();
                  conversationContext.dissociate(request);
              }
          }
      

       

      I use these two methods in following task processing method (more elegant would be to create an interceptor)

       

      @Schedule(second = "*/10", minute = "*", hour = "*", dayOfMonth = "*", month = "*", dayOfWeek = "*")
          public void processTask() {
              initConversationContext();
              task.execute();
              cleanupConversationContext();
          }