#
Timer Service
This tutorial explains ou what a Timer Service
in EJB is.
In order to create a timer in your Java EJB in the programmatically you have to inject the TimerService into your EJB using @Resource.
Here it is an example of Timer Service in Java/ EJB :
package ejb;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
@Singleton
@Startup
public class AddIntegers implements AddIntegersRemoteInterface {
@Resource
private TimerService timerService;
@PostConstruct
private void init() {
timerService.createTimer(5000, 5000, null);
}
@Timeout
public void execute(Timer timer) {
System.out.println("Java procedure executed at " + new Date());
System.out.println(returnSuma(1,3));
System.out.println("____________________________________________");
}
@Override
public int returnSuma(int a, int b) {
// What the EJB3 will return
return a+b;
}
}
This EJB will run the execute(Timer timer) method at every 5 seconds.
Using annotations to create a scheduled task is really easy as well. Take an EJB, add one @Schedule annotation or multiple @Schedule annotations as parameters of a @Schedules annotation to a method. Adding a Scheduler to an EJB is similar to adding a Timer.