package test; import java.io.Serializable; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerService; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; @Stateless public class MyTimerBean implements MyTimer { private static final Logger LOG = Logger.getLogger(Timer.class.getName()); private static final long MS = 2000; private static volatile long counter = 0; @Resource private TimerService timerService; public void initTimers() { try { stopAllTimers(); createTimer(MS); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to init", e); } } @SuppressWarnings("unused") @Timeout @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void timerTriggered(final Timer timer) { LOG.warning("Count " + counter++); } private void createTimer(long nextCallMs) { timerService.createTimer(nextCallMs, nextCallMs, null); } @SuppressWarnings("unchecked") private void stopAllTimers() { LOG.warning("Stopping all timers"); for (final Timer timer : (Collection) timerService.getTimers()) { timer.cancel(); } } }