I'm a new user of Java EE and I'm developing an application that has to update weather periodically. I created an automatic timer using the annotation, in order to update every 5 minutes. I would like to change to time dinamically ( an administrator can change it):
@Schedule(minute="*/5",hour = "*", persistent = false)
public void weatherUpdate(){
}
I would need an integer variable called frequency that contains the frequency of weather updates. I tried to do something like this, but this didn't worked:
int freq=5;
@Schedule(minute="*/freq",hour = "*", persistent = false)
public void weatherUpdate(){
}
Do you know any solution?
A possible solution is use a TimerService , for example you can create programmatic timers.
Eg.
@Singleton
@Startup
public class ProgrammaticTimer {
@Resource
TimerService timerService;
public void createTimer(String timerId, int frec){
ScheduleExpression expression = new ScheduleExpression();
expression.minute("*/"+freq).hour("*");
timerService.createCalendarTimer(expression, new TimerConfig(timerId, true));
}
@Timeout
public void execute(){
System.out.println("----Invoked: " + System.currentTimeMillis());
}
}
To edit a frequency of a timer, first you need cancel the current timer and create new timer with the new value.
Eg.
@Singleton
@Startup
public class ProgrammaticTimer {
@Resource
TimerService timerService;
public void createTimer(String timerId, int freq){
ScheduleExpression expression = new ScheduleExpression();
expression.minute("*/"+freq).hour("*");
timerService.createCalendarTimer(expression, new TimerConfig(timerId, true));
}
public void editTimer(String timerId, int freq){
cancelTimer(timerId)
ScheduleExpression expression = new ScheduleExpression();
expression.minute("*/"+freq).hour("*");
timerService.createCalendarTimer(expression, new TimerConfig(timerId, true));
}
public void cancelTimer(String timerId) {
if (timerService.getTimers() != null) {
for (Timer timer : timerService.getTimers()) {
if (timer.getInfo().equals(timerId)) {
timer.cancel();
}
}
}
}
@Timeout
public void execute(){
System.out.println("----Invoked: " + System.currentTimeMillis());
}
}
See also: Using the Timer Service
I hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.