[英]Stop/Start all method annotated with @Schedule in EJB 3.1
I need to stop and start all methods annotated with @Schedule in my EJBs classes. 我需要停止并启动所有在EJBs类中以@Schedule注释的方法。
For example I would like to stop and after few minutes restart doIt() method in that EJB class : 例如,我想停止并在几分钟后重新启动该EJB类中的doIt()方法:
@Stateless
public class MySchedule {
@Schedule(second = "*/15", minute = "*", hour = "*", persistent = false)
public void doIt(){
// do anything ...
}
}
I tried to use EJB Interceptors , like this code : 我尝试使用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();
}
}
But intercept method never fired by @Schedule 但是@Schedule从未触发过拦截方法
What you can do is to have a "Container" class with all of the classes annotated with @Scheduled
. 您可以做的是创建一个“容器”类,所有类都用@Scheduled
注释。 However, the problem with breaking/exit a method would rely on a condition/variable that keeps the code running or emits a signal of stop. 但是,中断/退出方法的问题将取决于保持代码运行或发出停止信号的条件/变量。
I'd do something like: 我会做类似的事情:
@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
}
}
}
The "Container" class: “容器”类:
@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.