1

我想在 Quartz 2.2.1 的周一和周二上午 10:00(例如)每两周触发一次工作。

我想使用CronTrigger,但不幸的是,无法为“每 2 周”设置一次 cron 作业(请参阅此处的解释)。使用CalendarIntervalTrigger似乎也不适合,因为我找不到工作日的支持。

这个 Quartz 有解决方案吗?

4

3 回答 3

1

The key idea is using a cron trigger for the "Monday and Tuesday at 10:00am". As that cron trigger will fire every week, you have to implement the "every two weeks" parts by yourself. So for calculating the next fire time after a certain date you let the cron trigger give you its next fire time and check whether you're in the correct week. If not you add an offset to get in the correct week.

This all can be done by overriding AbstractTrigger. As an example I'll show one of the key methods, getFireTimeAfter:

public class MyTrigger extends AbstractTrigger<MyTrigger> {

    //your cron trigger for Monday and Tuesday at 10:00am
    private OperableTrigger trigger;        

    //initialize this with the first fire time in method computeFirstFireTime
    private Date firstFireTime;     

    //fire every N weeks
    private int nboWeeks;

//...

    @Override
    public Date getFireTimeAfter(Date afterTime) {

        //Get the fire time of the cron trigger after afterTime
        Date cronFireTime = trigger.getFireTimeAfter(afterTime);

        //we have to determine whether we're in the correct week        
        int weeksSinceFirstFire = ...; //calculate the nbo weeks since firing for the first time
        int weekOffset = weeksSinceFirstFire % nboWeeks;

        //we won't fire any more or are in the correct week
        if (cronFireTime == null || weekOffset == 0) {
            return cronFireTime;
        }

        int weeksToAdd = weeksSinceFirstFire - weekOffset;
        Date fireTime = ...; // add weeksToAdd to cronFireTime

        return fireTime;
    }
//...
}
于 2014-06-16T07:13:39.223 回答
0

在 Quartz 的工作日 a 和 b 的 x 点每 n 周执行一次作业

要在周一和周二上午 10 点运行作业,我们需要首先确定周一和周二的最新日期。然后将这些日期用作 CalendarIntervalTrigger 的开始日期。

从今天开始识别最晚/下周一和周二的日期。代码可以在这里找到。然后在 Quartz calendarIntervalSchedule 上应用日期。

 //dd.M.yyyy hh:mm:ss a
 //Monday
 String getMondayDate = "23 JUNE 2014 10:0:0 am"
 String MONDAY = getMondayDate;

 Date startDate = new SimpleDateFormat("dd.M.yyyy hh:mm:ss a").parse(MONDAY);

 Trigger trigger = newTrigger()
    .withIdentity("mondayTrigger", "group1")
    .startAt(startDate)  //put retrieved monday date here
    .withSchedule(calendarIntervalSchedule()
            .withIntervalInWeeks(2)) // interval is set in calendar weeks
    .build();

//Tuesday
String getTuedayDate = "24 JUNE 2014 10:0:0 am"
String TUESDAY = getTuesdayDate;

Date startDate = new SimpleDateFormat("dd.M.yyyy hh:mm:ss a").parse(TUESDAY);

Trigger trigger = newTrigger()
    .withIdentity("mondayTrigger", "group1")
    .startAt(startDate)  //put retrieved monday date here
    .withSchedule(calendarIntervalSchedule()
        .withIntervalInWeeks(2)) // interval is set in calendar weeks
    .build();
于 2014-06-19T02:27:14.057 回答
0

这应该实现克隆接口。否则触发器会得到错误的触发时间。

于 2015-01-30T09:31:38.770 回答