Java : Quartz scheduler - is there a way I can get next five runs of a scheduled job

♀尐吖头ヾ 提交于 2019-12-11 16:28:29

问题


Is there any API which gives the next n runs of a cron expression.


回答1:


Quartz jobs are scheduled using a Trigger (org.quartz.Trigger). The trigger interface exposes two useful methods:

Date getNextFireTime();
Date getFireTimeAfter(Date afterTime);

So, take your Trigger, call getNextFireTime(). Now you know when it'll fire next. Then call getFireTimeAfter( next ) and pass it in the next fire time. Repeat until you have enough run times for your use case.

So, for five runs, something like this should work:

List<Date> getNextFiveRuns(Trigger trigger) {
    List<Date> runs = new ArrayList<>();
    Date next = trigger.getNextFireTime();

    // check for null, which indicates a non-repeating trigger or one with an end-time
    while(next != null && runs.size() < 5) {
      runs.add(next);
      next = trigger.getFireTimeAfter(next);
    }
    return runs;
}

Quartz 2.3.0 JavaDoc: org.quartz.Trigger




回答2:


You can calculate next run times like this:

import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.SimpleTriggerContext;

public static void main(String[] args) {
    CronTrigger trigger = new CronTrigger("0 0 10 * * ?");
    SimpleTriggerContext triggerContext = new SimpleTriggerContext();
    Date testDate = new Date();
    int i = 0;
    while (i++ < 5) {
        triggerContext.update(null, null, testDate);
        testDate = trigger.nextExecutionTime(triggerContext);
        System.out.println(testDate);
    }
}

And output is:

    Wed Jun 05 10:00:00 CEST 2019
    Thu Jun 06 10:00:00 CEST 2019
    Fri Jun 07 10:00:00 CEST 2019
    Sat Jun 08 10:00:00 CEST 2019
    Sun Jun 09 10:00:00 CEST 2019



回答3:


If you are looking to just understand, you can use http://www.cronmaker.com/ to calculate the next few scheduled run times

Looks like cronmaker has an API as well(I see you have mentioned you are looking for API) :

curl http://www.cronmaker.com/rest/sampler?expression={expression}

Example:

curl http://www.cronmaker.com/rest/sampler?expression=0 0/2 * 1/1 * ? *&hour=13&minute=45

Source:

http://www.cronmaker.com/help/rest-api-help.html



来源:https://stackoverflow.com/questions/56451154/java-quartz-scheduler-is-there-a-way-i-can-get-next-five-runs-of-a-scheduled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!