package dk.thoerup.schedulesamples; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.TimedObject; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerService; /* GFv3: before using a timed bean make sure the ejb timer service is correctly configured with a datasource and the timer table is created * cd /glassfish/domains/domain1/lib/databases/ejbtimer * /usr/lib/jvm/java-6-sun/db/bin/ij * connect 'jdbc:derby:.'; * paste content from /glassfish/lib/install/databases/ejbtimer_derby.sql * and content from /glassfish/lib/install/databases/upgrade/ejbtimer_upgrade_derby.sql (need the applicationID column) * after this make sure that all the files are owned by the user your GFv3 instance is running as * */ @Stateless public class TimedEjb /*implements TimedObject*/ { public static class TimerInfo implements Serializable { static final long serialVersionUID = 1L; private long start = System.currentTimeMillis(); public long getStart() { return start; } } private int count; //storing shared data like this is not recommended !!! @Resource private SessionContext sessionCtx; public void startTimer() { TimerService timerService = sessionCtx.getTimerService(); TimerInfo info = new TimerInfo(); //the info object is not necessary - but can be used to store data with the timer //Timer timer = timerService.createTimer( (5 * 1000), info); //singleshot timer timerService.createTimer(10*1000, 5000, info ); //repeating timer // otherwise use schedule expression to create more complex schedules // in this case fire once every minute when the seconds is == 10 //ScheduleExpression se = new ScheduleExpression().second(10).minute("*").hour("*"); //System.out.println(se.toString()); //timerService.createCalendarTimer( se ); count = 0; } //@Override if we used TimedObject interface //public void ejbTimeout(Timer timer) { //@Timeout public void myEjbTimeout(Timer timer) { TimerInfo info = (TimerInfo) timer.getInfo(); //any updates to the info object is not pushed back to the timer services System.out.print("timeout .... " + count + " / " + info.getStart() ); count++; if (count >= 10) { timer.cancel(); } } }