Quartz scheduler-Time between

别来无恙 提交于 2019-12-10 11:44:43

问题


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

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