package examples.timer; import javax.ejb.*; import javax.annotation.Resource; import java.util.Calendar; import java.util.TimeZone; import java.util.SimpleTimeZone; import java.util.GregorianCalendar; import java.util.Date; @Stateless public class CleanDayLimitOrdersBean implements CleanDayLimitOrders { @Resource private SessionContext ctx; public void cleanPeriodicallyDayLimitOrders() { // Get hold of the eastern time zone assuming that the securities are being // traded on NYSE and NASDAQ exchanges. String[] timezoneIDs = TimeZone.getAvailableIDs (-5 * 60 * 60 * 1000); SimpleTimeZone est = new SimpleTimeZone (-5 * 60 * 60 * 1000, timezoneIDs[0]); // Provide the rules for start and end days of daylight savings time. est.setStartRule (Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); est.setEndRule (Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); // Get hold of a calendar instance for the eastern time zone. Calendar cal = new GregorianCalendar(est); // Set the calendar to the current time. cal.setTime (new Date ()); // Calculate the difference between now and market close i.e. 4 PM Eastern. int hourofday = cal.get (cal.HOUR_OF_DAY); int minuteofhour = cal.get (cal.MINUTE); // If this method is invoked after the market close, then set the timer expiration // immediately i.e. start=0. Otherwise, calculate the milliseconds that needs // to elapse until first timer expiration. long start = 0; if (hourofday < 16) { int hourdiff = 16 - hourofday - 1; int mindiff = 60 - minuteofhour; start = (hourdiff * 60 * 60 * 1000) + (mindiff * 60 * 1000); } // Finally, get hold of the timer service instance from EJBContext object and create the // recurrent expiration timer. TimerService timerService = ctx.getTimerService(); Timer timer = timerService.createTimer(start, 86400000, null); System.out.println("CleanDayLimitOrdersBean: Timer created to first expire after " + start + " milliseconds."); } @Timeout public void handleTimeout(Timer timer) { System.out.println("CleanDayLimitOrdersBean: handleTimeout called."); // Put here the code for cleaning the database of day limit orders that have // not been executed. } }