我正在使用 EJB 3.1。 在下面的代码中,我尝试创建一个每年重复的计时器:
ScheduleExpression scheduleExpression = new ScheduleExpression();
Date now = new Date();
scheduleExpression.start(now);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
scheduleExpression.minute(calendar.get(Calendar.MINUTE));
scheduleExpression.hour(calendar.get(Calendar.HOUR_OF_DAY));
scheduleExpression.dayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
scheduleExpression.month(calendar.get(Calendar.MONTH));
但它不起作用,实际上行为是相当随机的(在某些重复中有效,而在另一些重复中则不然)。
奇怪的是,我也有每月重复(请参阅下面的代码)并且它正在工作。
ScheduleExpression scheduleExpression = new ScheduleExpression();
Date now = new Date();
scheduleExpression.start(now);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
scheduleExpression.minute(calendar.get(Calendar.MINUTE));
scheduleExpression.hour(calendar.get(Calendar.HOUR_OF_DAY));
scheduleExpression.dayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
有什么想法吗?
最佳答案
对于 Java 中的公历,月份的实现是从零开始的,如 Calendar 的 javadoc 中所述。 :
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
月份ScheduleExpression是基于一的:
month : one or more months within a year
Allowable values :
- [1,12]
- {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", Dec"}
因此,下面的代码构造 ScheduleExpression ,其中月份是过去一个月(或者在一月值 0 的情况下是无效参数,但无效情况下的行为似乎没有严格指定)。
Date now = new Date();
...
scheduleExpression.dayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
关于java - 每年定时器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512808/