我尝试将EJB编程计时器与IBM Liberty Profile 18.0.0.1一起使用。这是我的service.xml:
<feature>ejbLite-3.2</feature>
......
<ejbContainer>
<timerService nonPersistentMaxRetries="3" nonPersistentRetryInterval="10" />
</ejbContainer>
这是我的裸骨代码片段。
@Stateless
public class BatchSubmissionTimer {
private static final Logger LOGGER =
Logger.getLogger(BatchSubmissionTimer.class.getName());
@Resource
TimerService timerService;
private Date lastProgrammaticTimeout;
public void setTimer(long intervalDuration) {
LOGGER.info("Setting a programmatic timeout for "
+ intervalDuration + " milliseconds from now.");
Timer timer = timerService.createTimer(intervalDuration,
"Created new programmatic timer");
}
@Timeout
public void programmaticTimeout(Timer timer) {
this.setLastProgrammaticTimeout(new Date());
LOGGER.info("Programmatic timeout occurred.");
}
public String getLastProgrammaticTimeout() {
if (lastProgrammaticTimeout != null) {
return lastProgrammaticTimeout.toString();
} else {
return "never";
}
}
public void setLastProgrammaticTimeout(Date lastTimeout) {
this.lastProgrammaticTimeout = lastTimeout;
}
}
这是我的客户端调用计时器的方式:
BatchSubmissionTimer batchSubmissionTimer = new BatchSubmissionTimer();
batchSubmissionTimer.setTimer(5000);
但是,我在注入的TimerService上遇到了非指针错误。 TimerService未成功注入。任何人都可以对此有所了解吗?欣赏它!
在您的示例中,您将实例化您自己的BatchSubmissionTimer实例,而不是允许容器将其作为EJB提供,因此容器没有机会为带注释的timerService字段注入值。有几种方法可以将它作为EJB访问,包括查找或注入它,例如,
@EJB
BatchSubmissionTimer batchSubmissionTimer;