Java Reference
In-Depth Information
LISTING 10-3: (continued)
import javax.ejb.Timer;
import javax.ejb.TimerService;
@Singleton
@Startup
public class AllTimers {
@Resource
TimerService timerService;
@PostConstruct
public void manageTimer(){
Collection<Timer> timers = timerService.getAllTimers();
for(Timer t : timers){
System.out.println("Timer Info: " + t.getInfo());
System.out.println("Time Remaining: " + t.getTimeRemaining());
t.cancel();
}
}
}
In Listing 10‐3, the bean is instantiated at start‐up, and the manageTimer method is called. You
retrieve a collection of all the active timers and iterate over the collection, printing out the timer info
and the number of milliseconds that will elapse before the next scheduled timer expiration. Finally,
you cancel the timer.
Transactions
Beans create timers within a transaction that the container manages. If this transaction is rolled
back, so is the timer. If this transaction is rolled back then the timer is also rolled back. This means
that its creation is rolled back and if it were canceled the cancellation would be undone and the
timer reinstated. In listing 10‐4 we show an example of a timer method marked with a transaction
annotation.
LISTING 10‐4: A timer can set a transaction attribute
package com.devchronicles.timer;
import javax.annotation.Resource;
import javax.ejb.Timeout;
import javax.ejb.TimerService;
public class SimpleProgramaticTimer {
@Resource
 
Search WWH ::




Custom Search