java如何在部署时启动EJB计时器?
我需要创建一个间隔计时器,设置为每周自动运行一次。我不希望它基于用户输入启动,但我希望它在应用程序部署到服务器时创建。我看到的每个例子都有另一个类启动计时器。我不想使用消息驱动的bean来创建计时器,因为审计应该只查询给定时间段的数据库,而不是基于发送消息的操作
我已经包括了一个计时器的例子。在下面的示例中,计时器应每10分钟启动一次。作为测试,我希望计时器每10分钟启动一次,这样我就可以测试计时器
@Stateless
public class TimerTest implements
TimerTestLocal, TimerTestRemote{
@Resource
private TimerService timerService;
private Logger log = Logger.getLogger(TimerTest.class);
private long interval = 1000 * 60 * 10;
private static String TIMER_NAME = "AuditTimer";
public void scheduleTimer() throws NamingException {
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
//cal.set(Calendar.HOUR_OF_DAY, 23);//run at 11pm
//cal.set(Calendar.MINUTE, 00);
//cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
log.debug("schedule for: " + sdf.format(cal.getTime()));
timerService.createTimer(cal.getTime(), interval, TIMER_NAME);
}
public void cancelTimer() {
for(Object obj : timerService.getTimers())
{
Timer timer = (Timer)obj;
if(timer.getInfo().equals(TIMER_NAME))
timer.cancel();
}
}
@Timeout
public void timerEvent(Timer timer) {
log.debug("timer fired");
}
}
那么,有什么方法可以在应用程序部署时启动这个计时器呢?我认为将计时器的创建放在@PostConstruct方法中不是一个好主意,因为服务器上有类装入器
# 1 楼答案
我过去做计时器的方法是在web上创建一个上下文侦听器。xml来配置计时器
这样你就可以确保它是从容器启动的,当应用被关闭时,它会干净地关闭
# 2 楼答案
我不知道使用contextListener启动计时器是否有效。从本文how to use EJb 3 timer in a weblogic 10 cluster来看,您可能会在weblogic 10.3.2中遇到一些问题
# 3 楼答案
如果你的项目可以使用jee6/ejb3。1.这个问题有更好的解决办法。 http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html
通过使用新的@Schedule注释,您可以广泛控制何时以及多久调用一次超时方法。最大的好处是:你不再需要“从外面”启动计时器
甲骨文写道: