Sample Code:
@Singleton
@Startup public class EBlastScheduler {
@Resource
TimerService timerService;
EBlastScheduler what = new EBlastScheduler();
@PostConstruct
public void initialize(){
if (timerService.getTimers() != null) {
for (Timer timer : timerService.getTimers()) {
if (timer.getInfo().equals("EBlastScheduler")){
timer.cancel();
}
}
}
ScheduleExpression expression = new ScheduleExpression();
expression.second("*/1").minute("*").hour("*");
timerService.createCalendarTimer(expression);
}
@Timeout
public void execute(Timer timer){
System.out.println("----Invoked: " + System.currentTimeMillis());
} }
I just wanted to make a timer service that can handle the change in schedule of its timeout by canceling the former schedule if the new one is set. In my case, I can’t figure out how to do this in EJB 3.1 especially because I am new to this framework. Your help will be mostly appreciated. 😀
I want something like this:
EBlastScheduler ebs = new EBlastScheduler(ScheduleExpression sExp); //
this line of code must change the current scheduled time of the scheduler to the newly set’ed
time.
NOTE:
I wanted to access this class remotely; and by passing new
schedule as parameter/s, this class must change its timeout
accordingly.
You can have stateless a bean, which can be used as a utility for managing timers in the system. It will be responsible for performing operations on them – create/cancel timers.
The purpose is to decouple the timer operations from the startup class, then you can modify them at particular point of time.
But utility bean must be initialized before
EBlastScheduler, which is a startup bean, for that you have to annotate it with the annotation@DependsOn("TimerUtilityBean").Below is the sample code, might need some modifications.
EBlastScheduler.java
TimerUtilityBean.java
Now, you can use
TimerUtilityBeanto manage timers from anywhere within the application. Can access it remotely & will be able to pass new schedule parameters.