问题
I am using the Quartz Scheduler (version 1.8.3 due to project constraints) and I as assigned the task of creating an "MS Outlook-like" scheduler for Jobs specific to my project. Everything seems fine to work fine but I have a really huge problem with CronTriggers (this problem also exists in version 2.1 of Quartz):
I am using CronTriggers for recurrence patterns of DAILY, WEEKLY and MONTHLY. In addition to the recurrence pattern, I also provide an option for 'No. of occurrences'. This has become the bane of my life! CronTrigger does not provide an option for 'repeatCount' like SimpleTriggers do (bug: https://jira.terracotta.org/jira/browse/QTZ-242?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel). Apparently this may be fixed in version 2.2 but I cannot wait that long nor do I believe my problem is unique!
A few options that I deemed worthy of investigation:
Calculate the 'EndTime' for the CronTrigger but using my own logic - this fails to cover all possible cases and is only approximate at best even for simple cases.
Use a TriggerListener or JobListener to keep track of no. of iterations of the job since I just need the job to stop after 'N' iterations and I have a 1:1 mapping from Job instance to Trigger. This does not seem very feasible and/or efficient by any stretch of the imagination.
Could any of you who have used CronTriggers with the option of 'No. of occurrences' please give some insights on how to solve this conundrum?
回答1:
It seems that Quartz have implemented something that can help: TriggerUtils.computeEndTimeToAllowParticularNumberOfFirings.
I haven't tested it yet, but this is the code I have wrote for now:
CronTrigger trigger = newTrigger()
.withSchedule(cronSchedule(cronExpression))
.build();
Date endDate = TriggerUtils.computeEndTimeToAllowParticularNumberOfFirings((OperableTrigger) trigger,
new BaseCalendar(Calendar.getInstance().getTimeZone()), 10);
trigger = trigger.getTriggerBuilder().endAt(endDate).build();
If this won't work, then as said here and here, you can't set a repeat count, and you should use TriggerListener.
In any case, version 2.2 doesn't have this feature.
Update
I've tested it, and it works.
回答2:
Wy dont't you instead use the Simple Trigger? You would have the additional taks of calculating the time interval at the time of scheduling the job, but that will be a one time activity.
来源:https://stackoverflow.com/questions/8692098/how-to-simulate-no-of-occurrences-or-repeat-count-with-crontriggers-in-java