我需要在EJB类中停止并启动所有使用@Schedule注释的方法。
例如,我想停止并在几分钟后重新启动该EJB类中的doIt()方法:
@Stateless
public class MySchedule {
@Schedule(second = "*/15", minute = "*", hour = "*", persistent = false)
public void doIt(){
// do anything ...
}
}
我尝试使用EJB拦截器,如下代码:
@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
解雇答案 0 :(得分:0)
你可以做的是拥有一个“容器”类,其中所有类都注明了@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.
}
}