问题
I am using quartz scheduler for scheduling jobs.I have a case where i want to execute a job every day night(9:00 PM) to next day morning(06:00 AM).How can i achieve this.Currently i am initializing trigger like this
Trigger trigger2 = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
What modification i need to make to satisfy the requirement?
回答1:
If you have opt for the Quartz CronExpression you can use an expression like this 0 * 21-23,0-5 ? * *
that fire a job every minute every day from 00:00 AM to 05:59 AM and from 9:00 PM to 23:59 PM, so:
trigger = newTrigger()
.withIdentity("trigger7", "group1")
.withSchedule(cronSchedule("0 * 21-23,0-5 ? * *"))
.build();
Remember to import the import static org.quartz.CronScheduleBuilder.cronSchedule
The frequency (in this example every minute) depends on your requirement.
回答2:
If your need is to run a job ONCE every day you need to only specify the start time of the job:
newTrigger().withSchedule(
CronScheduleBuilder.dailyAtHourAndMinute(21,0)).build();
Quartz scheduler can't help you if the scheduled job (database processing) takes many hours and it might get over the 6AM time limit. Quartz only starts the job. You should stop yourself the running job at 6AM. For example suppose the job is a method:
public void doSomeDBOperations() {
while(have more data to process) {
if(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == 6) {
break;
}
//insert data
}
}
回答3:
Here is a ref you may use this to schedule time using quartz. Java – Job Scheduling in web application with quartz API
This part might help you
JobDetail jDetail = new JobDetail("Newsletter", "NJob", MyJob.class);
//"0 0 12 * * ?" Fire at 12pm (noon) every day
//"0/2 * * * * ?" Fire at every 2 seconds every day
CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?");
来源:https://stackoverflow.com/questions/14208056/quartz-scheduler-time-between