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

javadev picture javadev · Apr 12, 2013 · Viewed 12.2k times · Source

I'm new to the @Schedule annotations in J2EE6

I want to run a job using EJB 3.x with Glassfish 3.1.

The javax.ejb.Schedule seems to be a good choice for us, so we could think of our custom time as something like:

@Singleton
public class CustomTimer {
    @EJB
    SettingsFacade settingsFacade;

    @Schedule(second="someSecondParameter", minute="someMinuteParameter",hour="someHourParameter", persistent=false)
    public void executeTimer(){
        //Code executing something against database using the settingsFacade
    }
}

Here, we want the parameters to be got from database, so they are changed every month. Any clean solution for this?

Answer

Sólon Soares picture Sólon Soares · Nov 21, 2016
@Singleton
@Startup
public class ScheduleTimerService {

    @Resource private TimerService timerService;

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

    @PostConstruct
    private void postConstruct() {
        timerService.createCalendarTimer(createSchedule());
    }

    @Timeout
    public void timerTimeout(Timer timer) {
           Add your code here to be called when scheduling is reached...
           in this example: 01h:30m every day ;-)
    }

    private ScheduleExpression createSchedule(){

        ScheduleExpression expression = new ScheduleExpression();
        expression.dayOfWeek("Sun,Mon,Tue,Wed,Thu,Fri,Sat");    
        expression.hour("01");
        expression.minute("30");

        return expression;
    }
}