EJB @Schedule wait until method completed

后端 未结 4 771
陌清茗
陌清茗 2020-11-30 22:52

I want to write a back-ground job (EJB 3.1), which executes every minute. For this I use the following annotation:

@Schedule(minute = \"*/1\", hour = \"*\")
         


        
4条回答
  •  隐瞒了意图╮
    2020-11-30 23:05

    I ran into the same problem but solved it slightly differently.

    @Singleton
    public class DoStuffTask {
    
        @Resource
        private TimerService timerSvc;
    
        @Timeout
        public void doStuff(Timer t) {
            try {
                doActualStuff(t);
            } catch (Exception e) {
                LOG.warn("Error running task", e);
            }
            scheduleStuff();
        }
    
        private void doActualStuff(Timer t) {
    
            LOG.info("Doing Stuff " + t.getInfo());
        }
    
        @PostConstruct
        public void initialise() {
            scheduleStuff();
        }
    
        private void scheduleStuff() {
            timerSvc.createSingleActionTimer(1000l, new TimerConfig());
        }
    
        public void stop() {
            for(Timer timer : timerSvc.getTimers()) {
                timer.cancel();
            }
        }
    
    }
    

    This works by setting up a task to execute in the future (in this case, in one second). At the end of the task, it schedules the task again.

    EDIT: Updated to refactor the "stuff" into another method so that we can guard for exceptions so that the rescheduling of the timer always happens

提交回复
热议问题