I am attempting to use TimerService with an entity bean in an EJB3.0 application. I have spent a couple of days looking for a way to get the EntityContext so that I can call EntityContext.getTimerService(). The problem is that EJB3.0 entity beans annotated with @Entity don't support @Resource injection. I have tried implementing the setEntityContext() method but, given that I am not implementing javax.ejb.EntityBean, that unsuprisingly didn't work. How do I get the EntityContext from an entity bean annotated with @Entity? Is there a different way to get the TimerService? My code follows:
@Entity
@Table(name = "periodic_script")
public class PeriodicScript {
private static final long serialVersionUID = 1;
// Entity bean properties
.
.
.
private EntityContext ctx;
public void setEntityContext(EntityContext ec) {
this.ctx = ec;
}
.
.
.
@PostPersist
public void scheduleScriptExecution() {
ctx.getTimerService().createTimer(Calendar.getInstance().getTime(), getPeriod() * 1000, getId());
}
@Timeout
public void executeScript(Timer timer) {
// logic to execute when timeout occurs
.
.
.
}
@PreRemove
public void removeTimer() {
for (Object timerObject : ctx.getTimerService().getTimers()) {
Timer timer = (Timer) timerObject;
if (timer.getInfo().equals(getId())) {
timer.cancel();
}
}
}
.
.
.
}
"Timers can be created for stateless session beans, message-driven beans, and 2.1 entity beans.
Timers cannot be created for stateful session beans[94] or EJB 3.0 entities."
So you can't use timer in class annotted by @Entity