使用Schedule Expression参数化EJB调度程序

时间:2017-02-15 06:21:13

标签: java ejb scheduler ejbscheduler

我正在使用EJB 3.1和jboss-eap-6.4,我想为ejb调度程序的小时,分​​钟和秒设置一些动态参数,如下所示:

非参数代码 - 每5分钟运行30秒:

@Singleton
@Startup
public class TriggerJob {
    @EJB
   //some db injections           

    @PostConstruct
    public void onStartup() {
        try {
            preparation();
        } catch (CertificateVerificationException e) {
            e.printStackTrace();
        }
    }

    @Schedule(second = "30", minute = "*/5", hour = "*", persistent = false)
    public void preparation() {
    //my scheduled tasks
    }
}

上面的代码正确执行。

动态参数代码 - 应该每5分钟30秒运行一次:

@Singleton
@Startup
public class TriggerJob {

    @EJB
    //some injections

    private boolean runningFlag = false;

    @Resource
    private TimerService timerService;

    public void setTimerService(TimerService timerService) {
        this.timerService = timerService;
    }

    @Timeout
    public void timerTimeout() {
        try {
            preparation();
        } catch (CertificateVerificationException e) {
            e.printStackTrace();
        }
    }

    @PostConstruct
    private void postCunstruct() {
        timerService.createCalendarTimer(createSchedule(),new TimerConfig("EJB timer service timeout at ",false));
    }

    private ScheduleExpression createSchedule() {
        ScheduleExpression expression = new ScheduleExpression();
        expression.hour("*")
                .minute("*/5")
                .second("30");
        return expression;
    }

    public void preparation(){
    // my scheduled tasks
    }
}

上面的代码没有正确执行,通常它会在一秒钟内执行多次。

另外,我已经阅读了其他一些对我没有帮助的问题:

Dynamic parameters for @Schedule method in an EJB 3.x

Using the Timer Service - The Java EE 6 Tutorial

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

相反,使用程序化调度,这是一个例子:

@Singleton
@Startup
public class TriggerJob{

    @EJB
    //some injections

    @Resource
    private TimerService timerService;

    @PostConstruct
    public void init() {
        createTimer();
        //the following code resolve my startup problem
        try {
        preparation();
        } catch (CertificateVerificationException e) {
            e.printStackTrace();
        }
    }

    @Timeout
    public void timerTimeout() {
        try {
        preparation();
        } catch (CertificateVerificationException e) {
        e.printStackTrace();
        }
    }

    private void createTimer() {
        ScheduleExpression scheduleExpression = new ScheduleExpression();
        scheduleExpression.second("30").minute("*/5").hour("*");
        TimerConfig timerConfig = new TimerConfig();
        timerConfig.setPersistent(false);
        timerService.createCalendarTimer(scheduleExpression, timerConfig);
        }

    public void preparation(){
        // my scheduled tasks
    }
}