目前我正在使用以下配置来安排我的调度程序。
@Schedule(second ="1/10", minute = "*", hour = "*")
private void scheduleUser() {
try {
new UserFacade().insertUserInfo();
} catch (Exception e) {
logger.error("Error in : " + e);
}
}
现在我想在运行时设置计时器值而不是硬编码方式。假设我有一个bean调用Property
,它有一个名为frequency
的字段。
现在我想为new Property().getFrequency()
调度程序设置EJB
之类的值。
有没有办法做一些像下面这样的事情?
@Schedule(second =new Property().getFrequency(), minute = "*", hour = "*")
private void scheduleUser() {
try {
new UserFacade().insertUserInfo();
} catch (Exception e) {
logger.error("Error in : " + e);
}
}
答案 0 :(得分:2)
没有注释,没有。您必须使用程序化计时器(Java 7,EE7):
package com.foo;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Singleton;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
@Singleton
public class MyTimer {
@Resource
private TimerService timerService;
@Timeout
public void timeout(Timer timer) {
System.out.println("TimerBean: timeout occurred");
}
public void schedule(Date start, long intervalMilis) {
try{
timerService.createTimer(start, intervalMilis, "my timer");
} catch (EJBException|IllegalArgumentException|IllegalStateException ex) {
Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
}
}
}
有关详细信息,请参阅https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples004.htm。
答案 1 :(得分:0)
类似于Vegard提交的答案,除了使用ScheduleExpression的答案。 更多信息Beginning Java EE 7 book
import javax.ejb.ScheduleExpression;
@Singleton
public class MyTimer {
@Resource
private TimerService timerService;
@Timeout
public void timeout(Timer timer) {
System.out.println("TimerBean: timeout occurred");
}
public void schedule(String DOW, String H, String M, String S) {
try{
ScheduleExpression scheduleExpression = new ScheduleExpression();
scheduleExpression.dayOfWeek(DOW);
scheduleExpression.hour(H);
scheduleExpression.minute(M);
scheduleExpression.second(S);
timerService.createCalendarTimer(scheduleExpression, new TimerConfig(this, false));
} catch (EJBException|IllegalArgumentException|IllegalStateException ex) {
Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
}
}
}