I'm deploying an EJB which should set a timer and be triggered by it every 24 hours. But where should I set the timer? @PostConstruct
does not help -- this is a session bean, so post-construct method will be invoked when the actual instance is created (this never happens as the sole purpose of this bean is to track timer).
Is there any other way to get notification about the bean deployment (not instantiation) in order to set up timer there?
Thanks
The EJB timer service provides a reliable and transactional notification service for timed events. Timer notifications may be scheduled to occur at a specific time, after a specific elapsed duration, or at specific recurring intervals. You can define callback methods on your EJB to receive these time-based events.
EJB Container calls the method, which is annotated by @Timeout. EJB Timer Service is a service provided by EJB container, which helps to create timer and to schedule callback when timer expires.
Nonpersistent programmatic timers are created by calling TimerConfig. setPersistent(false) and passing the TimerConfig object to one of the timer-creation methods.
EJB 3.1 introduces the Singleton bean. It will be created at deplyoment of the EJB.
@Singleton
@Startup
public class TimerSessionBean {
@Resource
TimerService timerService;
@PostConstruct
public void startTimer() {
Logger.getLogger(getClass().getName()).log(Level.INFO,
timerService.getTimers().size() + " timers running");
Logger.getLogger(getClass().getName()).log(Level.INFO, "create a timer");
timerService.createTimer(10000, 10000, "a timer");
}
@Timeout
void doSomething(Timer timer) {
System.out.println("something");
}
}
Another new feature in EJB 3.1 which can be used to run a task periodically is the Schedule annotation.
I think that the easiest and most portable solution is to add a web-application to your enterprise-application with a context listener (contextInitialized event) that initializes the ejb.
By the way, that's more or less what the Quartz Scheduler does as well (class QuartzInitializerListener)
The solution I found is ugly, but just as ugly as any other legal solution to this problem (e.g. solution from @fvu). Applying @WebService
annotation to the bean make JBoss instantiate it immediately after deployment (because it needs the way to construct the bean's WSDL), so @PostConstruct
-marked method will be invoked. I was able to set a timer from there.
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