Xavizo
Xavizo

Reputation: 69

Java Quartz-scheduler between time

I have job which i want to start using quartz scheduler (v2.1.5) in specific time everyday (eg. 8am-10am with interval 5 min) with no using cron expression, just native methods. (by native methods i understand implemented in that quartz lib). I have Trigger:

TriggerBuilder builder = TriggerBuilder.newTrigger()
                .withIdentity(name, group)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInMilliseconds(interval)
                        .repeatForever());

Of course cron expression dosent make difficult and I can use it instead. But anyway i just would know if using native methods in that problem is possible. Happy to any advices!

Upvotes: 0

Views: 3198

Answers (2)

Matthias
Matthias

Reputation: 2775

Here is an example from the Quartz tutorial (modified a bit):

var cal = new DailyCalendar(8, 0, 0, 0, 10, 0, 0, 0); // range start and end hours, minutes, seconds and millis
cal.setInvertTimerange(true); // by default the date interval specified above is excluded from execution. 
// This turns it around and only allows execution within the interval

var t2 = TriggerBuilder.newTrigger()
    .withIdentity("myTrigger2")
    .forJob("myJob2")
    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMilliseconds(interval)
                    .repeatForever());
    .modifiedByCalendar(cal)
    .build();

The trick is to have a simple trigger (like you showed above) but then have a calendar implementation that can specify times when execution of that trigger is allowed.

Upvotes: 2

walen
walen

Reputation: 7273

The API methods cover several simple (every X, at X) and not-so-simple (days A, B, C at X, monthly at X) scenarios, but yours is a bit beyond that.
You could try this to get a job scheduled to run every 5 minutes, 8am to 10am:

Trigger trigger = TriggerBuilder.newTrigger() // identity, job, etc.
        .withSchedule(simpleSchedule()
                .withIntervalInMinutes(5)
                .repeatForever())
        .startAt(DateBuilder.tomorrowAt(8,0,0))
        .endAt(DateBuilder.tomorrowAt(10,0,0))
        .build();

And then include some logic in your job to reschedule itself for the next day in the same way, upon finishing.
Alternatively, you can just schedule it to run every 5 minutes forever, and have the job check if it's between 8am and 10am before doing anything.

Or you could use, you know... a cron expression:

Trigger trigger = TriggerBuilder.newTrigger() // identity, job, etc.
        .withSchedule(cronSchedule("0 0/5 8-10 * * ? *"))
        .startAt(DateBuilder.evenMinuteDateAfterNow())
        .build();

Which does exactly what you want -- that's what cron expressions are for.

Upvotes: 1

Related Questions