Cron expression for every five minutes in the next n hours?

53,179

Solution 1

I think should be able to define a trigger that can repeat every hour until a certain time:

import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

...

Trigger myTrigger = newTrigger()
                    .withIdentity('myUniqueTriggerID")
                    .forJob(myJob)
                    .startAt(startDate)
                    .endAt(endDate)
                    .withSchedule(simpleSchedule().withIntervalInHours(1));

...

scheduler.scheduleJob(myJob, myTrigger);

Solution 2

Use the range operator to specify the hours. For example, for running the job every five minutes for 10 hours starting at 2 am:

0 0/5 2-12 * * *

Here is an excellent tutorial on Cron expression and operators: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

Edit: 10/3/2016: Updated the link.

Solution 3

If you can programatically access the CronTrigger that is running your cron expression then you can call the methods setStartTime and setEndTime with the computed time range.

Alternatively you could construct the cron expression on the fly and specify a computed hour range.

For example if you are starting your server at 9am you could create this expression at runtime 0 0/5 9-19 * * *

Share:
53,179
Alex Pi
Author by

Alex Pi

Updated on September 07, 2020

Comments

  • Alex Pi
    Alex Pi over 3 years

    I know every five minutes is:

    0 0/5 * * * *
    

    But how do I limit the number hours for this to happen?

    Example: Every five minutes for the next 10 hours.

  • Alex Pi
    Alex Pi over 10 years
    That is a valid answer. Problem is that my code is client of an EJB that deals with quartz API. I only can provide startTime and cron expression.
  • Alex Pi
    Alex Pi over 10 years
    It seems I can't do what I want with a single cron expression.
  • Morfic
    Morfic over 10 years
    Not sure I fully understand the problem. Could you please provide a more detailed explanation of the problem? Also perhaps you could use the - special character to define the interval. Take a look at quartz-scheduler.org/api/2.0.0/org/quartz/CronExpression.htm‌​l
  • Alex Pi
    Alex Pi over 10 years
    I don't have control on quartz API. I am just calling an EJB that receives a startTime (date object) and the cron expression. Yes, at the end I used "-" computing the range I should set there. Still thinking about special cases here... like switching from one day to another in a computed range.
  • Alex Pi
    Alex Pi over 10 years
    In a general context (having access to the quartz API) your answer is correct.
  • Khurram
    Khurram over 7 years
    Updated the link.