3

目前我正在使用以下配置来安排我的调度程序。

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

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

现在我想new Property().getFrequency()EJB调度程序设置值。

有什么办法可以做类似以下的事情吗?

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

2 回答 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

于 2013-11-19T07:27:11.323 回答
0

类似于 Vegard 提交的答案,除了这个使用 ScheduleExpression。更多信息Java EE 7 入门书籍

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);
        }
    }

}
于 2013-11-19T16:26:12.460 回答