问题
I need to run a daily job which will run once a day and get some data from a different database. The task is developed as an EJB. I tried the @Schedule with EJB, and it is working fine. But the issue is if there is a change in the schedule, the code has to be changed and the app to be redeployed. Is there a way to avoid this? May be by using configuration files etc. I am using JSF 2.2, glassfish3.4.2 in CentOS.
回答1:
You can do this by creating your timer programmatically something like this
....
private static final String TIMER_NAME = "SOME_TIMER_NAME";
....
@Resource
TimerService timerService;
....
public void createTimer(String days, String hours, String minutes) {
removeTimer();
ScheduleExpression scheduleExpression = new ScheduleExpression();
if (days != null) {
scheduleExpression.dayOfMonth(datys);
}
if (hours != null) {
scheduleExpression.hour(hours);
}
if (minutes != null) {
scheduleExpression.minute(minutes);
}
TimerConfig timerConfig = new TimerConfig();
timerConfig.setInfo(TIMER_NAME);
Timer timer = timerService.createCalendarTimer(scheduleExpression, timerConfig);
}
private void removeTimer() {
for (Timer timer : timerService.getTimers()) {
if (TIMER_NAME.equals(timer.getInfo())) {
timer.cancel();
}
}
}
@Timeout
public void retrieveData() {
// retrieve data from DBs
}
now calling the createTimer method like this
createTimer("*", "3", null);
retrieveData() method will be executed at 3:00 AM each day. If you want to change the schedule you should call the method with appropriate values. You may tune it to meet your requirements like add input validation, define parameters differently etc. You may want to look at ScheduleExpression to find what is best for you. My code just shows an idea.
回答2:
Did you consider using cron job? here are some examples: Cron examples
来源:https://stackoverflow.com/questions/22031538/best-way-to-schedule-a-job-in-glassfish-centos