javacontainersejb-3.0java-ee-5

Stop a scheduled EJB task in Java EE


I have below scheduled bean which runs discovery method every two minutes.

@Stateless(name="MySchedulerBean)
public class MySchedulerBean    
     @Schedule(persistent=false, minute="*/2", hour="*", timezone="GMT"
     public void discover(){
          //run discovery every 2 minute
     } 
}

The problem with above approach is that it runs forever. Is there any way to stop the method to kick once my discovery is done? Can I conditionally run/stop ?


Solution

  • Two approaches: you could just set a boolean on your bean and have discover() check that boolean for whether it ought to run. This will still lead to discover() being invoked every two minutes though, only to do nothing. But this will allow you to add a resumeDiscovery() method to pick up at a later date.

    @Stateless(name="MySchedulerBean)
    public class MySchedulerBean
         private boolean cancelTimer = false;
    
         public void stopDiscovery() {
            this.cancelTimer = true;
         }
    
         @Schedule(persistent=false, minute="*/2", hour="*", timezone="GMT"
         public void discover() {
              if (cancelTimer) {
                   return;
              }
              //run discovery
         } 
    }
    

    Alternatively, you can cancel the Timer that is handling the job. This is a more permanent solution; you won't be able to restart this scheduled EJB... at least, not easily. That would look like this:

    @Stateless(name="MySchedulerBean)
    public class MySchedulerBean
         private boolean cancelTimer = false;
    
         public void stopDiscovery() {
            this.cancelTimer = true;
         }
    
         @Schedule(persistent=false, minute="*/2", hour="*", timezone="GMT"
         public void discover(Timer timer) {
              if (cancelTimer) {
                   timer.cancel();
                   return;
              }
              //run discovery
         } 
    }
    

    So now, if you decide to stop discovery, the next time discovery tries to run, the timer on this bean will be cancelled for good.