I've a requirement which requires 3-6 scheduled task to run at a given time of the day. I am completely new to EJB timers, but have read that EJB timers is the best way to handle scheduled task in a Java EE container.
Design Question:
Let's say I need 10 scheduled tasks. I don't want to have, if possible, 10 EJB timers created. Instead I would like to have a one off EJB timer created and then reuse this for creating as much scheduled jobs as requried, passing the scheduled time to run (as aruguements) for each instance, to is this possible? Can someone please help with a skeleton code on this please?
N.B I am thinking of using non-persistent EJB timers ...
Another option (in addition to alreay said) is to use singleton with @Schedule annotation for each of your timed methods:
@Singleton
@Startup
public class TimedTaskManager {
@Schedule(second = "0", minute = "*/5", hour = "*")
public void runTask1() {
//
}
@Schedule(second = "15", minute = "*/5", hour = "6,7,8")
public void runTask2() {
//
}
//
//
@Schedule(second = "0", minute = "*", hour = "1,2,6")
public void runTaskN() {
//
}
}
You could define a timer in one of your stateless/message driven bean business methods (you'd still have to call it, though, it's not possible to create a timer that would start off on its own). Then, in the @Timeout method you could recreate the timer based on any logic you find suitable, i.e.
@Stateless
public SomeEJB ... {
@Resource
private TimerService timerService;
public void businessMethod() {
timerService.createTimer(...);
}
@Timeout
public void timeout(Timer timer) {
// do some timer-related logic, recreate the timer,
// perhaps with new duration
timerService.createTimer(...);
}
}
This example is EJB 3.0-compatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With