[英]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.