Execute service method periodically

强颜欢笑 提交于 2019-12-12 02:55:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!