简体   繁体   English

在Java EE中停止计划的EJB任务

[英]Stop a scheduled EJB task in Java EE

I have below scheduled bean which runs discovery method every two minutes. 我下面有预定的bean,它每两分钟运行一次发现方法。

@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 ? 我可以有条件地运行/停止吗?

Two approaches: you could just set a boolean on your bean and have discover() check that boolean for whether it ought to run. 两种方法:您可以在bean上设置一个布尔值,然后使用discover()检查该布尔值是否应该运行。 This will still lead to discover() being invoked every two minutes though, only to do nothing. 尽管如此,这仍将导致discover()每两分钟被调用一次,但是什么也不做。 But this will allow you to add a resumeDiscovery() method to pick up at a later date. 但是,这将允许您添加resumeDiscovery()方法以在以后使用。

@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. 至少不容易,您将无法重新启动此计划的EJB。 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. 因此,现在,如果您决定停止发现,而下次尝试运行发现时,此bean上的计时器将被永久取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM