问题
So, I have a service:
@Stateless
public void SomeService {
public void someAction() {
...
}
}
And I have a config file timer.properties
which contains following string:
refresh.interval=1234
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()
.
回答1:
Your class must implement TimerDemoRemote interface
@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() {
...
}
}
Hope this helps..
回答2:
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.
来源:https://stackoverflow.com/questions/27386639/execute-service-method-periodically