3

我正在使用 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
    }
}

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

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

EJB 3.x 中 @Schedule 方法的动态参数

使用计时器服务 - Java EE 6 教程

任何帮助,将不胜感激。

4

1 回答 1

2

相反,使用编程调度,这里是一个例子:

@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
    }
}
于 2017-02-19T20:23:33.737 回答