定期执行服务方式 [英] Execute service method periodically
问题描述
所以,我有一个服务:
@Stateless
public void SomeService {
public void someAction() {
...
}
}
我有一个配置文件 timer.properties
其中包含以下字符串:
And I have a config file timer.properties
which contains following string:
refresh.interval=1234
问题是找到如何自动执行 someAction()
每1234秒?我试过 @Schedule
,但它只适用于常量。应用程序必须从config(已经使用 @Startup .. @PostConstruct
bean方法实现)读取值,并将此值设置为 someMethod()的执行间隔,
。
The question is to find how to automatically execute someAction()
every 1234 seconds? I tried @Schedule
, but it works only with constants. The application must read value from config (already implemented with @Startup.. @PostConstruct
bean method) and set this value as execution interval for someMethod()
.
推荐答案
感谢大家,我发现可接受的回答自己。因此,如果您需要定期在EJB中调用一些方法,那么可以在EJB规范中使用优秀的 TimerService
来实现。
Thanks everyone, I found acceptable answer myself. So, if you need to call some method in your EJB periodically, you could do it with excellent TimerService
in EJB spec.
可能的解决方案之一是:
One of possible solutions will be following:
@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();
}
}
有关更多信息,请参阅这个和 链接。
For more info, see this and that links.
这篇关于定期执行服务方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!