所以,我有一项服务:
@Stateless
public void SomeService {
public void someAction() {
...
}
}
我有一个配置文件timer.properties
,其中包含以下字符串:
refresh.interval=1234
问题是找到如何每1234秒自动执行someAction()
?我试过@Schedule
,但它只适用于常量。应用程序必须从config读取值(已使用@Startup.. @PostConstruct
bean方法实现)并将此值设置为someMethod()
的执行间隔。
答案 0 :(得分:0)
您的类必须实现TimerDemoRemote接口
@Stateless
public void SomeService implements TimerDemoRemote{
@Resource
private SessionContext context;
public void MyTimer(long duration) {
//There are many variants of createTimer you can choose the one that you require.
context.getTimerService().createTimer(Long initialDuration,long intervalDuration,Serializable info);
}
@Timeout
public void doMyTask(Timer timer){
//call those methods that you require I mean someAction() etc..
}
public void someAction() {
...
}
}
希望这会有所帮助..
答案 1 :(得分:0)
谢谢大家,我自己找到了可以接受的答案。因此,如果需要定期在EJB中调用某个方法,那么可以在EJB规范中使用优秀的TimerService
来实现。
可能的解决方案之一将是:
@Singleton
@Startup
public class RepeatableService {
@EJB
private SomeService service;
@Resource
private TimerService timerService;
private long repeatInterval = 1234000L; // in milliseconds
@PostConstruct
public void init() {
timerService.createIntervalTimer(0L,
repeatInterval, new TimerConfig(null, false));
}
@Timeout
public void process(Timer timer) {
doAction();
}
public void doAction() {
System.out.println("Action called!");
service.someAction();
}
}