有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在EJB调度中设置计时器值?

目前,我正在使用以下配置来安排我的计划程序

 @Schedule(second ="1/10", minute = "*", hour = "*")
 private void scheduleUser() {      
    try {
        new UserFacade().insertUserInfo();            
    } catch (Exception e) {
        logger.error("Error in : " + e);
    }
 }

现在我想在运行时设置计时器值,而不是用硬编码的方式。假设我有一个bean调用Property,它有一个名为frequency的字段

现在我想为EJB调度器设置new Property().getFrequency()之类的值

有没有什么方法可以做到像下面这样的事情

 @Schedule(second =new Property().getFrequency(), minute = "*", hour = "*")
 private void scheduleUser() {      
    try {
        new UserFacade().insertUserInfo();            
    } catch (Exception e) {
        logger.error("Error in : " + e);
    }
 }

共 (2) 个答案

  1. # 1 楼答案

    与Vegard提交的答案类似,除了这个答案使用ScheduleExpression。 更多信息Beginning Java EE 7 book

    import javax.ejb.ScheduleExpression;
    
    @Singleton
    public class MyTimer {
    
        @Resource
        private TimerService timerService;
    
        @Timeout
        public void timeout(Timer timer) {
            System.out.println("TimerBean: timeout occurred");
        }
    
        public void schedule(String DOW, String H, String M, String S) {
            try{
                ScheduleExpression scheduleExpression = new ScheduleExpression();
                scheduleExpression.dayOfWeek(DOW); 
                scheduleExpression.hour(H); 
                scheduleExpression.minute(M); 
                scheduleExpression.second(S); 
    
                timerService.createCalendarTimer(scheduleExpression, new TimerConfig(this, false));
            } catch (EJBException|IllegalArgumentException|IllegalStateException ex)  {
                Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
            }
        }
    
    }
    
  2. # 2 楼答案

    不需要注释。必须使用编程计时器(Java 7,EE7):

    package com.foo;
    
    import java.util.Date;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.annotation.Resource;
    import javax.ejb.EJBException;
    import javax.ejb.Singleton;
    import javax.ejb.Timeout;
    import javax.ejb.Timer;
    import javax.ejb.TimerService;
    
    @Singleton
    public class MyTimer {
        @Resource
        private TimerService timerService;
    
        @Timeout
        public void timeout(Timer timer) {
            System.out.println("TimerBean: timeout occurred");
        }
    
        public void schedule(Date start, long intervalMilis) {
            try{
                timerService.createTimer(start, intervalMilis, "my timer");            
            } catch (EJBException|IllegalArgumentException|IllegalStateException ex)  {
                Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
            }
        }
    }
    

    详见https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples004.htm