void createTimerWithPeriod(TimerService timerService, TimerType timerType, long timerOffset, Period period) { if (isTimerCreated(timerType, timerService)) { return; } TimerConfig config = new TimerConfig(); config.setInfo(timerType); Date startDate = getDateForNextTimerExpiration(period, timerOffset); ScheduleExpression schedleExpression = getExpressionForPeriod(period, startDate); Timer timer = timerService.createCalendarTimer(schedleExpression, config); Date nextStart = timer.getNextTimeout(); SimpleDateFormat sdf = new SimpleDateFormat(); logger.logInfo(Log4jLogger.SYSTEM_LOG, LogMessageIdentifier.INFO_TIMER_CREATED, String.valueOf(timerType), sdf.format(nextStart)); }
ScheduleExpression getExpressionForPeriod(Period period, Date startDate) { Calendar cal = Calendar.getInstance(); cal.setTime(startDate); ScheduleExpression schedleExpression = new ScheduleExpression(); schedleExpression.start(startDate); if (period == Period.DAY) { schedleExpression.second(cal.get(Calendar.SECOND)); schedleExpression.minute(cal.get(Calendar.MINUTE)); schedleExpression.hour(cal.get(Calendar.HOUR_OF_DAY)); } else if (period == Period.MONTH) { schedleExpression.second(cal.get(Calendar.SECOND)); schedleExpression.minute(cal.get(Calendar.MINUTE)); schedleExpression.hour(cal.get(Calendar.HOUR_OF_DAY)); schedleExpression.dayOfMonth(cal.get(Calendar.DAY_OF_MONTH)); } return schedleExpression; }
@Test public void initTimers_interval() throws Exception { // given TimerServiceStub timeServiceStub = mock(TimerServiceStub.class); when(ctx.getTimerService()).thenReturn(timeServiceStub); TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo(TimerType.BILLING_INVOCATION); doReturn(new TimerStub(null, timerConfig)).when(timeServiceStub) .createCalendarTimer(any(ScheduleExpression.class), any(TimerConfig.class)); // when tm.initTimers(); // then verify(timeServiceStub, times(4)).createTimer(any(Date.class), eq(10000L), any(TimerType.class)); }
@Test public void getExpressionForPeriod_dayPeriod_midnight() { // given Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date startDate = cal.getTime(); // when ScheduleExpression result = tm.getExpressionForPeriod(Period.DAY, startDate); // then assertEquals(startDate.getTime(), result.getStart().getTime()); assertEquals("0", result.getSecond()); assertEquals("0", result.getMinute()); assertEquals("0", result.getHour()); }
@SuppressWarnings({ "deprecation" }) @Test public void getExpressionForPeriod_monthPeriod() { // given Date startDate = new Date(System.currentTimeMillis() + 10000); // when ScheduleExpression result = tm.getExpressionForPeriod(Period.MONTH, startDate); // then assertEquals(startDate.getTime(), result.getStart().getTime()); assertEquals(String.valueOf(startDate.getSeconds()), result.getSecond()); assertEquals(String.valueOf(startDate.getMinutes()), result.getMinute()); assertEquals(String.valueOf(startDate.getHours()), result.getHour()); assertEquals(String.valueOf(startDate.getDate()), result.getDayOfMonth()); }
@SuppressWarnings({ "deprecation" }) @Test public void getExpressionForPeriod_monthPeriod_midnightOfFirstDay() { // given Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date startDate = cal.getTime(); // when ScheduleExpression result = tm.getExpressionForPeriod(Period.MONTH, startDate); // then assertEquals(startDate.getTime(), result.getStart().getTime()); assertEquals("0", result.getSecond()); assertEquals("0", result.getMinute()); assertEquals("0", result.getHour()); assertEquals(String.valueOf(startDate.getDate()), result.getDayOfMonth()); }
/** * <p>Starts the The Timer Scheduler to handle Mail Synchronization.</p> */ @PostConstruct public void startup() { LOG.info("Starting IWS Mail Synchronize Bean."); // Registering the Timer Service. This will ensure that the Scheduler // is invoked at frequent intervals. final TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("IWS Mail Synchronize"); timerConfig.setPersistent(false); final ScheduleExpression expression = new ScheduleExpression(); final String[] time = settings.getMailSynchronizeTime().split(":", 2); expression.hour(time[0]).minute(time[1]); timerService.createCalendarTimer(expression, timerConfig); LOG.info("First synchronize run scheduled to begin at {}", expression); }
public BatchJobConfiguration fireUpTimer(BatchJobConfiguration jobConfig) { if (jobConfig.isActive()) { logger.debug("Configured batch job " + jobConfig.getType().getDisplayName()); TimerConfig timerConf = new TimerConfig(jobConfig, false); String[] splittedCronJob = jobConfig.getCronJobExpression().split(" "); ScheduleExpression schedExp = new ScheduleExpression(); schedExp.second(splittedCronJob[0]); schedExp.minute(splittedCronJob[1]); schedExp.hour(splittedCronJob[2]); schedExp.dayOfMonth(splittedCronJob[3]); schedExp.month(splittedCronJob[4]); schedExp.year(splittedCronJob[5]); schedExp.dayOfWeek(splittedCronJob[6]); Timer timer = timerService.createCalendarTimer(schedExp, timerConf); jobConfig.setNextTimeout(timer.getNextTimeout()); jobConfig = batchJobConfigurationDAO.update(jobConfig); } return jobConfig; }
/** * Reads the schedule definition from the given configuration subset. Handles the hour, minute, day of week, day of * month, and month values. * * @param config * configuration subset * @return configured schedule object to be used with a timer */ private ScheduleExpression readSchedule(Configuration config) { ScheduleExpression expression = new ScheduleExpression(); if (config.containsKey(SCHEDULE_HOUR)) { expression.hour(config.getString(SCHEDULE_HOUR)); } if (config.containsKey(SCHEDULE_MINUTE)) { expression.minute(config.getString(SCHEDULE_MINUTE)); } if (config.containsKey(SCHEDULE_DAY_OF_WEEK)) { expression.dayOfWeek(config.getString(SCHEDULE_DAY_OF_WEEK)); } if (config.containsKey(SCHEDULE_DAY_OF_MONTH)) { expression.dayOfMonth(config.getString(SCHEDULE_DAY_OF_MONTH)); } if (config.containsKey(SCHEDULE_MONTH)) { expression.month(config.getString(SCHEDULE_MONTH)); } return expression; }
/** * Processes the first step which is entry of the login information. * @return step2 */ public String processFirstStep() { if(!email.equals(confirmEmail)) { String emailMustMatch = bundle.getString(ResourceBundleKeys.step1_emailMustMatch.getKey()); FacesContext.getCurrentInstance().addMessage(emailConfirmComp.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR,emailMustMatch,emailMustMatch)); // TODO check the database to see if we already have a user with the same name return null; } ScheduleExpression se = new ScheduleExpression(); se.month(2).dayOfMonth(14).year(2012).hour(11).minute(30); flyerBean.scheduleFlyer(se,new Email()); step1 = true; return NAVIGATION_STEP_2; }
@PostConstruct private void initialize() { log.info("IoCWithCustomProtostreamGenerator initialize..."); new File(GENERATED_PROTOFILES_DIRECTORY).mkdirs(); if (SINKIT_ALL_IOC_PROTOSTREAM_GENERATOR_D_H_M_S != null) { timerService.createCalendarTimer(new ScheduleExpression() .dayOfWeek(SINKIT_ALL_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[0]) .hour(SINKIT_ALL_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[1]) .minute(SINKIT_ALL_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[2]) .second(SINKIT_ALL_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[3]) , new TimerConfig(ALL_IOC_TAG, false)); log.info("IoCWithCustomProtostreamGenerator: All IoC Protostream Generator"); } if (SINKIT_ALL_CUSTOM_PROTOSTREAM_GENERATOR_D_H_M_S != null) { timerService.createCalendarTimer(new ScheduleExpression() .dayOfWeek(SINKIT_ALL_CUSTOM_PROTOSTREAM_GENERATOR_D_H_M_S[0]) .hour(SINKIT_ALL_CUSTOM_PROTOSTREAM_GENERATOR_D_H_M_S[1]) .minute(SINKIT_ALL_CUSTOM_PROTOSTREAM_GENERATOR_D_H_M_S[2]) .second(SINKIT_ALL_CUSTOM_PROTOSTREAM_GENERATOR_D_H_M_S[3]) , new TimerConfig(ALL_CUSTOM_TAG, false)); log.info("IoCWithCustomProtostreamGenerator: All Custom Protostream Generator"); } }
@PostConstruct private void initialize() { new File(GENERATED_PROTOFILES_DIRECTORY).mkdirs(); if (SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S != null) { timerService.createCalendarTimer(new ScheduleExpression() .dayOfWeek(SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S[0]) .hour(SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S[1]) .minute(SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S[2]) .second(SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S[3]) , new TimerConfig("CustomlistProtostreamGenerator", false)); } else { log.info("CustomlistProtostreamGenerator timer not activated."); } }
@Test public void testAsScheduleExpression(){ final CronDefinition cronDefinition = TestCronDefinitionsFactory.quartzNoDoWAndDoMRestrictionBothSameTime(); final CronParser cronParser = new CronParser(cronDefinition); final Cron cron = cronParser.parse("0 * * 1 * MON *"); ScheduleExpression expression = cron.asScheduleExpression(); assertNotNull(expression); assertEquals(cron.retrieve(CronFieldName.SECOND).getExpression().asString(), expression.getSecond()); assertEquals(cron.retrieve(CronFieldName.MINUTE).getExpression().asString(), expression.getMinute()); assertEquals(cron.retrieve(CronFieldName.HOUR).getExpression().asString(), expression.getHour()); assertEquals(cron.retrieve(CronFieldName.DAY_OF_MONTH).getExpression().asString(), expression.getDayOfMonth()); assertEquals(cron.retrieve(CronFieldName.MONTH).getExpression().asString(), expression.getMonth()); assertEquals(cron.retrieve(CronFieldName.DAY_OF_WEEK).getExpression().asString(), expression.getDayOfWeek()); assertEquals(cron.retrieve(CronFieldName.YEAR).getExpression().asString(), expression.getYear()); }
@Override public Timer createTimer(final Object primaryKey, final Method timeoutMethod, final ScheduleExpression scheduleExpression, final TimerConfig timerConfig) { if (scheduleExpression == null) { throw new IllegalArgumentException("scheduleExpression is null"); } //TODO add more schedule expression validation logic ? checkState(); try { final TimerData timerData = timerStore.createCalendarTimer(this, (String) deployment.getDeploymentID(), primaryKey, timeoutMethod, scheduleExpression, timerConfig, false); initializeNewTimer(timerData); return timerData.getTimer(); } catch (final TimerStoreException e) { throw new EJBException(e); } }
@Test(timeout = 1000) public void testIncrementsA() throws ParseException { final ScheduleExpression expr = new ScheduleExpression().year(2008).month(1).dayOfMonth(20) .hour("6/3").minute(30).start(new Date(0)); final EJBCronTrigger trigger = new EJBCronTrigger(expr); // Should fire on Sunday, January 20th, first at 6:30 Calendar calendar = new GregorianCalendar(2008, 0, 20); Date startTime = new Date(calendar.getTimeInMillis() - 1000); calendar.set(Calendar.HOUR_OF_DAY, 6); calendar.set(Calendar.MINUTE, 30); assertEquals(calendar.getTime(), trigger.getFireTimeAfter(startTime)); // Next on 9:30 startTime = new Date(calendar.getTimeInMillis()); calendar.set(Calendar.HOUR_OF_DAY, 9); assertEquals(calendar.getTime(), trigger.getFireTimeAfter(startTime)); // Won't be fired after the 20th so it should return null calendar = new GregorianCalendar(2008, 0, 21); startTime = new Date(calendar.getTimeInMillis()); assertNull(trigger.getFireTimeAfter(startTime)); }
@Test public void testManualConfiguration() { Timer timer = schedulerBean.setTimer("10", new Date()); ScheduleExpression scheduleExpression = timer.getSchedule(); scheduleExpression.hour(10); scheduleExpression.start(new Date()); assertEquals("The timer will start today at the 10", "10", scheduleExpression.getHour()); assertEquals("The timer will start each Wednesday too", "Wed", scheduleExpression.getDayOfWeek()); }
@Override public Timer createCalendarTimer(ScheduleExpression arg0) throws IllegalArgumentException, IllegalStateException, EJBException { return null; }
@Override public Timer createCalendarTimer(ScheduleExpression arg0, TimerConfig arg1) throws IllegalArgumentException, IllegalStateException, EJBException { TimerStub timer = new TimerStub(arg0, arg1); timers.add(timer); return timer; }
public TimerStub(ScheduleExpression scheduleExpression, TimerConfig config) { this.scheduleExpression = scheduleExpression; Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, 1); this.execDate = cal.getTime(); this.info = config.getInfo(); }
@SuppressWarnings({ "deprecation" }) @Test public void getExpressionForPeriod_dayPeriod() { // given Date startDate = new Date(System.currentTimeMillis() + 10000); // when ScheduleExpression result = tm.getExpressionForPeriod(Period.DAY, startDate); // then assertEquals(startDate.getTime(), result.getStart().getTime()); assertEquals(String.valueOf(startDate.getSeconds()), result.getSecond()); assertEquals(String.valueOf(startDate.getMinutes()), result.getMinute()); assertEquals(String.valueOf(startDate.getHours()), result.getHour()); }
/** * To ensure that the system State is always consistent, we have two things * that must be accomplished. First thing is to load the former state and * ensure that the system is working using this as base.<br /> * Second part is to have a timer service (cron job), which will once per * day run and perform certain cleanup actions.<br /> * This method is run once the Bean is initialized and will perform two * things, first it will initialize the Timer Service, so it can run at * frequent Intervals, secondly, it will initialize the Sessions.<br /> * Heavier maintenance operations like cleaning up accounts is left for * the Timed Service to handle, since it may otherwise put the server under * unnecessary pressure during the initial Startup Phase. */ @PostConstruct public void startup() { LOG.info("Starting IWS Initialization."); // First, we need to initialize our dependencies activeSessions = ActiveSessions.getInstance(settings); accessDao = new AccessJpaDao(entityManager, settings); exchangeDao = new ExchangeJpaDao(entityManager, settings); service = new AccountService(settings, accessDao, notifications); // Second, we're registering the Timer Service. This will ensure that the // Bean is invoked daily at 2 in the morning. final TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("IWS State Cleaner"); timerConfig.setPersistent(false); final ScheduleExpression expression = new ScheduleExpression(); final String[] time = settings.getRunCleanTime().split(":", 2); expression.hour(time[0]).minute(time[1]); timerService.createCalendarTimer(expression, timerConfig); LOG.info("First cleanup run scheduled to begin at {}", expression); if (settings.resetSessionsAtStartup()) { // Now, remove all deprecated Sessions from the Server. These Sessions // may or may not work correctly, since IW4 with JSF is combining the // Sessions with a Windows Id, and upon restart - the Windows Id is // renewed. Even if it isn't renewed, JSF will not recognize it final int deprecated = accessDao.deprecateAllActiveSessions(); LOG.info("Deprecated {} Stale Sessions.", deprecated); } else { loadActiveTokens(); } // That's it - we're done :-) LOG.info("IWS Initialization Completed."); }
private ScheduleExpression createScheduleExpression() { // Get schedule parameters from the configuration service ScheduleParameters scheduleParameters = configurationService.readScheduleParameters(); // build and return the ScheduleExpression as required by the TimerService ScheduleExpression schedule = new ScheduleExpression() .second(scheduleParameters.getSecond()) .minute(scheduleParameters.getMinute()) .hour(scheduleParameters.getHour()); return schedule; }
@PostConstruct public void startup() { log.info("Check if Database is up-to-date."); if (checkDatabase()) { log.info("Initialize the Settings."); initializeSettings(); log.info("Initializing the CWS Sanitizer Service."); // If requested, then simply start the sanitize as a background job // now. The job will process small blocks of code and save these. if (settings.getSanityStartup()) { runSanitizing(); } // Registering the Timer Service. This will ensure that the Scheduler // is invoked at frequent intervals. final TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("CWS Sanitizer"); // Once started, the next run should always occur as planned, regardless // of restarts, as it is not guaranteed that the sanitizing is performed // at startup. timerConfig.setPersistent(true); // Starting the Timer Service every hour. final ScheduleExpression expression = new ScheduleExpression(); expression.hour("*"); timerService.createCalendarTimer(expression, timerConfig); } }
/** * Converts the given schedule expression to a cron-like string. * * @param exp * expression to convert * @return cron-like string representing the given expression */ private String toString(ScheduleExpression exp) { if (exp == null) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(exp.getMinute()).append(' '); builder.append(exp.getHour()).append(' '); builder.append(exp.getDayOfMonth()).append(' '); builder.append(exp.getMonth()).append(' '); builder.append(exp.getDayOfWeek()); return builder.toString(); }
@PostConstruct public void setTimer() { // TODO: move the configuration to the properties table ScheduleExpression schedule = new ScheduleExpression(); schedule.second("4"); schedule.minute("*"); schedule.hour("*"); // schedule.hour("8, 13, 16"); schedule.dayOfWeek("Mon-Fri"); TimerConfig timerConfig = new TimerConfig(); timerConfig.setPersistent(false); timerService.createCalendarTimer(schedule, timerConfig); }
@PostConstruct private void initialize() { if (SINKIT_IOC_PROTOSTREAM_GENERATOR_D_H_M_S != null) { timerService.createCalendarTimer(new ScheduleExpression() .dayOfWeek(SINKIT_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[0]) .hour(SINKIT_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[1]) .minute(SINKIT_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[2]) .second(SINKIT_IOC_PROTOSTREAM_GENERATOR_D_H_M_S[3]) , new TimerConfig("IOCListProtostreamGenerator", false)); } else { log.info("IOCListProtostreamGenerator timer not activated."); } }
@PostConstruct private void initialize() { if (SINKIT_WHITELIST_PROTOSTREAM_GENERATOR_D_H_M_S != null) { timerService.createCalendarTimer(new ScheduleExpression() .dayOfWeek(SINKIT_WHITELIST_PROTOSTREAM_GENERATOR_D_H_M_S[0]) .hour(SINKIT_WHITELIST_PROTOSTREAM_GENERATOR_D_H_M_S[1]) .minute(SINKIT_WHITELIST_PROTOSTREAM_GENERATOR_D_H_M_S[2]) .second(SINKIT_WHITELIST_PROTOSTREAM_GENERATOR_D_H_M_S[3]) , new TimerConfig("WhitelistProtostreamGenerator", false)); } else { log.info("WhitelistProtostreamGenerator timer not activated."); } }