下面列出了怎么用javax.ejb.ScheduleExpression的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
@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);
}
}
@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());
}
@PostConstruct
private void construct() {
final TimerConfig plantTheCorn = new TimerConfig("plantTheCorn", false);
timerService.createCalendarTimer(new ScheduleExpression().month(5).dayOfMonth("20-Last").minute(0).hour(8), plantTheCorn);
timerService.createCalendarTimer(new ScheduleExpression().month(6).dayOfMonth("1-10").minute(0).hour(8), plantTheCorn);
final TimerConfig harvestTheCorn = new TimerConfig("harvestTheCorn", false);
timerService.createCalendarTimer(new ScheduleExpression().month(9).dayOfMonth("20-Last").minute(0).hour(8), harvestTheCorn);
timerService.createCalendarTimer(new ScheduleExpression().month(10).dayOfMonth("1-10").minute(0).hour(8), harvestTheCorn);
final TimerConfig checkOnTheDaughters = new TimerConfig("checkOnTheDaughters", false);
timerService.createCalendarTimer(new ScheduleExpression().second("*").minute("*").hour("*"), checkOnTheDaughters);
}
@Test
public void test() throws Exception {
final ScheduleExpression schedule = new ScheduleExpression()
.hour("*")
.minute("*")
.second("*/5");
scheduler.scheduleEvent(schedule, new TestEvent("five"));
Assert.assertTrue(events.await(1, TimeUnit.MINUTES));
}
private void addSchedulesToMethod(final MethodContext methodContext, final MethodScheduleInfo info) {
if (methodContext == null) {
return;
}
for (final ScheduleInfo scheduleInfo : info.schedules) {
final ScheduleExpression expr = new ScheduleExpression();
expr.second(scheduleInfo.second == null ? "0" : scheduleInfo.second);
expr.minute(scheduleInfo.minute == null ? "0" : scheduleInfo.minute);
expr.hour(scheduleInfo.hour == null ? "0" : scheduleInfo.hour);
expr.dayOfWeek(scheduleInfo.dayOfWeek == null ? "*" : scheduleInfo.dayOfWeek);
expr.dayOfMonth(scheduleInfo.dayOfMonth == null ? "*" : scheduleInfo.dayOfMonth);
expr.month(scheduleInfo.month == null ? "*" : scheduleInfo.month);
expr.year(scheduleInfo.year == null ? "*" : scheduleInfo.year);
expr.timezone(scheduleInfo.timezone);
expr.start(scheduleInfo.start);
expr.end(scheduleInfo.end);
final TimerConfig config = new TimerConfig();
config.setInfo(scheduleInfo.info);
config.setPersistent(scheduleInfo.persistent);
methodContext.getSchedules().add(new ScheduleData(config, expr));
}
}
public ScheduleExpression getSchedule() throws EJBException, IllegalStateException, NoSuchObjectLocalException {
checkState();
if (timerData.getType() == TimerType.Calendar) {
return ((CalendarTimerData) timerData).getSchedule();
}
throw new IllegalStateException("The target timer is not a calendar-based type ");
}
private void readObject(final ObjectInputStream in) throws IOException {
super.doReadObject(in);
autoCreated = in.readBoolean();
try {
scheduleExpression = ScheduleExpression.class.cast(in.readObject());
} catch (final ClassNotFoundException e) {
throw new IOException(e);
}
}
@Override
public TimerData createCalendarTimer(final EjbTimerServiceImpl timerService, final String deploymentId, final Object primaryKey, final Method timeoutMethod, final ScheduleExpression scheduleExpression, final TimerConfig timerConfig, final boolean auto)
throws TimerStoreException {
final long id = counter.incrementAndGet();
final TimerData timerData = new CalendarTimerData(id, timerService, deploymentId, primaryKey, timeoutMethod, timerConfig, scheduleExpression, auto);
getTasks().addTimerData(timerData);
return timerData;
}
@Override
public TriggerPropertyBundle loadExtendedTriggerProperties(final Connection conn, final TriggerKey triggerKey) throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(Util.rtp(SELECT_CRON_TRIGGER, tablePrefix, schedNameLiteral));
ps.setString(1, triggerKey.getName());
ps.setString(2, triggerKey.getGroup());
rs = ps.executeQuery();
if (rs.next()) {
final String cronExpr = rs.getString(COL_CRON_EXPRESSION);
final String timeZoneId = rs.getString(COL_TIME_ZONE_ID);
final String[] parts = cronExpr.split(EJBCronTrigger.DELIMITER);
try {
final EJBCronTrigger cb = new EJBCronTrigger(new ScheduleExpression()
.year(parts[0])
.month(parts[1])
.dayOfMonth(parts[2])
.dayOfWeek(parts[3])
.hour(parts[4])
.minute(parts[5])
.second(parts[6])
.timezone(timeZoneId));
return new TriggerPropertyBundle(new EJBCronTriggerSceduleBuilder(cb), null, null);
} catch (final EJBCronTrigger.ParseException e) {
throw new IllegalStateException("Can't build the Trigger with key: '" + triggerKey + "' and statement: " + Util.rtp(SELECT_CRON_TRIGGER, tablePrefix, schedNameLiteral));
}
}
throw new IllegalStateException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + Util.rtp(SELECT_CRON_TRIGGER, tablePrefix, schedNameLiteral));
} finally {
Util.closeResultSet(rs);
Util.closeStatement(ps);
}
}
private ScheduleExpression copy(final ScheduleExpression scheduleExpression) {
final ScheduleExpression scheduleExpressionCopy = new ScheduleExpression();
scheduleExpressionCopy.year(scheduleExpression.getYear());
scheduleExpressionCopy.month(scheduleExpression.getMonth());
scheduleExpressionCopy.dayOfMonth(scheduleExpression.getDayOfMonth());
scheduleExpressionCopy.dayOfWeek(scheduleExpression.getDayOfWeek());
scheduleExpressionCopy.hour(scheduleExpression.getHour());
scheduleExpressionCopy.minute(scheduleExpression.getMinute());
scheduleExpressionCopy.second(scheduleExpression.getSecond());
scheduleExpressionCopy.start(scheduleExpression.getStart());
scheduleExpressionCopy.end(scheduleExpression.getEnd());
scheduleExpressionCopy.timezone(scheduleExpression.getTimezone());
return scheduleExpressionCopy;
}
public EJBCronTrigger(final ScheduleExpression expr) throws ParseException {
final Map<Integer, String> fieldValues = new LinkedHashMap<>();
fieldValues.put(Calendar.YEAR, expr.getYear());
fieldValues.put(Calendar.MONTH, expr.getMonth());
fieldValues.put(Calendar.DAY_OF_MONTH, expr.getDayOfMonth());
fieldValues.put(Calendar.DAY_OF_WEEK, expr.getDayOfWeek());
fieldValues.put(Calendar.HOUR_OF_DAY, expr.getHour());
fieldValues.put(Calendar.MINUTE, expr.getMinute());
fieldValues.put(Calendar.SECOND, expr.getSecond());
timezone = expr.getTimezone() == null ? TimeZone.getDefault() : TimeZone.getTimeZone(expr.getTimezone());
setStartTime(expr.getStart() == null ? new Date() : expr.getStart());
setEndTime(expr.getEnd());
// If parsing fails on a field, record the error and move to the next field
final Map<Integer, ParseException> errors = new HashMap<>();
int index = 0;
for (final Entry<Integer, String> entry : fieldValues.entrySet()) {
final int field = entry.getKey();
final String value = entry.getValue();
try {
expressions[index++] = parseExpression(field, value);
} catch (final ParseException e) {
errors.put(field, e);
}
}
// If there were parsing errors, throw a "master exception" that contains all
// exceptions from individual fields
if (!errors.isEmpty()) {
throw new ParseException(errors);
}
rawValue = expr.getYear() + DELIMITER + expr.getMonth() + DELIMITER + expr.getDayOfMonth() + DELIMITER + expr.getDayOfWeek()
+ DELIMITER + expr.getHour() + DELIMITER + expr.getMinute() + DELIMITER + expr.getSecond();
}
@Test(timeout = 5000)
public void testSecond() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().hour("*").minute("*").second(5).start(new Date(0));
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 1, 5, 0, 0, 5).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 1, 5, 0, 0, 4).getTime()));
assertEquals(new GregorianCalendar(2011, 1, 5, 0, 1, 5).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 1, 5, 0, 0, 6).getTime()));
}
@Test(timeout = 5000)
public void testBothDayOfMonthAndDayOfWeekF() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().year(2011).dayOfMonth("19").dayOfWeek("3").hour(20).minute(59).second(59).start(new GregorianCalendar(2011, 4, 18, 20, 59, 58).getTime());
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 4, 18, 20, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 18, 20, 59, 58).getTime()));
assertEquals(new GregorianCalendar(2011, 4, 19, 20, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 18, 20, 59, 59).getTime()));
}
@Test(timeout = 5000)
public void testBothDayOfMonthAndDayOfWeekG() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().year(2011).dayOfMonth("12").dayOfWeek("6").hour(20).minute(59).second(59).start(new GregorianCalendar(2011, 5, 11, 20, 59, 58).getTime());
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
//assertEquals(new GregorianCalendar(2011, 5, 11, 20, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 5, 11, 20, 59, 58).getTime()));
assertEquals(new GregorianCalendar(2011, 5, 12, 20, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 5, 11, 20, 59, 59).getTime()));
}
@Test(timeout = 5000)
public void testLastDayOfMonthA() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfMonth("Last").hour(23).minute(59).second(59).start(new Date(0));
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2009, 1, 28, 23, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2009, 1, 1, 0, 0, 0).getTime()));
//Test Leap year
assertEquals(new GregorianCalendar(2000, 1, 29, 23, 59, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2000, 1, 28, 0, 0, 0).getTime()));
}
@Test(timeout = 5000)
public void testMinusDayOfMonth() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfMonth(-2).hour(23).minute(1).second(59).start(new Date(0));
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2009, 1, 26, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2009, 1, 1, 0, 0, 0).getTime()));
//Test Leap year
assertEquals(new GregorianCalendar(2000, 1, 27, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2000, 1, 26, 0, 0, 0).getTime()));
//Test next month
assertEquals(new GregorianCalendar(2000, 1, 27, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2000, 1, 26, 0, 0, 0).getTime()));
}
@Test(timeout = 5000)
public void testOrdinalNumbersDayOfMonthA() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfMonth("2nd mon").hour(23).minute(1).second(59).start(new Date(0));
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 4, 9, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 1, 0, 0, 0).getTime()));
assertEquals(new GregorianCalendar(2011, 5, 13, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 10, 0, 0, 0).getTime()));
}
@Test(timeout = 500)
public void testSimpleDayOfWeek() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfWeek("7").hour(23).minute(1).second(59).start(new Date(0));
;
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 4, 8, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 5, 23, 1, 30).getTime()));
}
@Test(timeout = 500)
public void testSimpleDayOfWeekA() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfWeek("0").hour(23).minute(1).second(59).start(new Date(0));
;
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 4, 8, 23, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 5, 23, 1, 30).getTime()));
}
@Test(timeout = 500)
public void testSimpleDayOfWeekB() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().dayOfWeek("5").hour(14).minute(1).second(59).start(new Date(0));
;
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(new GregorianCalendar(2011, 4, 6, 14, 1, 59).getTime(), trigger.getFireTimeAfter(new GregorianCalendar(2011, 4, 5, 23, 1, 30).getTime()));
}
@Test(timeout = 5000)
public void testSimpleDayOfWeekC() throws ParseException {
final ScheduleExpression expr = new ScheduleExpression().year(2011).month(6).dayOfWeek("3").hour(22).minute(1).second(1).start(new Date(0));
;
final EJBCronTrigger trigger = new EJBCronTrigger(expr);
assertEquals(null, trigger.getFireTimeAfter(new GregorianCalendar(2011, 5, 29, 23, 1, 1).getTime()));
}