繁体   English   中英

停止/启动在EJB 3.1中使用@Schedule注释的所有方法

[英]Stop/Start all method annotated with @Schedule in EJB 3.1

我需要停止并启动所有在EJBs类中以@Schedule注释的方法。

例如,我想停止并在几分钟后重新启动该EJB类中的doIt()方法:

@Stateless
public class MySchedule {

  @Schedule(second = "*/15", minute = "*", hour = "*", persistent = false)
  public void doIt(){
    // do anything ...
  }

}

我尝试使用EJB Interceptor,例如以下代码:

@Stateless
public class MySchedule {

  @Schedule(second = "*/15", minute = "*", hour = "*", persistent = false)
  @Interceptors(MyInterceptor.class)
  public void doIt(){
    // do anything ...
  }
}

public class MyInterceptor{
         @AroundInvoke
         public Object intercept(){
            System.out.println(" Schedule Intercepted");  
            Object result = context.proceed();
         }
}

但是@Schedule从未触发过拦截方法

您可以做的是创建一个“容器”类,所有类都用@Scheduled注释。 但是,中断/退出方法的问题将取决于保持代码运行或发出停止信号的条件/变量。

我会做类似的事情:

@Stateless
public class MySchedule implements Schedulable{
    boolean shouldRun = true;

    //This method should be present in the Schedulable interface
    @Override
    public synchronized boolean shouldBeRunning(boolean shouldRun){
      this.shouldRun = shouldRun;
    }

    //This method should also be in the Schedulable interface, so
    //you can invoke it wherever you need it.
    @Override
    @Schedule(second = "*/15", minute = "*", hour = "*", persistent = false)
    public void doIt(){
       /* If it runs a loop, you can break it like this: */
       while(shouldRun){
           //do anything
       }

       /* Otherwise you can break functionality of doIt and verify in each step: */
       if(shouldRun){
           //do anything step 1
       }

       if(shouldRun){
           //do anything step 2
       }

       if(shouldRun){
           //do anything step 3
       }
    }
}

“容器”类:

@Named
public class SchedulableContainer{
    @EJB
    MySchedule mySchedule;

    @EJB
    MyOtherSchedule myOtherSchedule;

    private Schedulable[] schedulables;

    @PostConstruct
    void initSchedulables(){
       schedulables = new Schedulable[]{ sched, sched2 };
    }

    void toggleSchedulables(boolean shouldRun){
        for(Schedulable sched: schedulables){
            sched.shouldBeRunning(shouldRun);
        }
    }

    public void stopSchedulables(){
        this.toggleSchedulables(false);
    }

    public void restartSchedulables(){
        this.toggleSchedulables(true);

        //Here you could read a property that tells you
        //how much should you delay to trigger MySchedule#doIt
        //again.
    }
}

暂无
暂无

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

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