Run Quartz Scheduler Job with specific start, end date and within time constraints

后端 未结 1 2026
滥情空心
滥情空心 2021-01-01 04:31

I am using Quartz-Scheduler for repetitive tasks but I am facing a trouble. In my server side my user wants to specify some date range like From 2013-

相关标签:
1条回答
  • 2021-01-01 05:19

    What is the error you get when you say it is not working?

    You can try the following code (Edit: applies to Quartz 2.2). This approach does not specify the start/end dates and year in the cron expression, instead uses the Trigger methods to specify them. (Note: I haven't tested it myself, let me know if it works for you)

    Edit: I had the chance to test this code, I ran the code below and kept changing the system clock and all triggers were successful between 9 am to 12 am from start to end date.

    public class CronJob {
    
        public static void main(String[] args) throws ParseException, SchedulerException {
    
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    
            JobDetail job = newJob(TestJob.class)
                .withIdentity("cronJob", "testJob") 
                .build();
    
            String startDateStr = "2013-09-27 00:00:00.0";
            String endDateStr = "2013-09-31 00:00:00.0";
    
            Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(startDateStr);
            Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(endDateStr);
    
            CronTrigger cronTrigger = newTrigger()
              .withIdentity("trigger1", "testJob")
              .startAt(startDate)
              .withSchedule(CronScheduleBuilder.cronSchedule("0 0 9-12 * * ?").withMisfireHandlingInstructionDoNothing())
              .endAt(endDate)
              .build();
    
            scheduler.scheduleJob(job, cronTrigger);
            scheduler.start();
        }    
    
        public static class TestJob implements Job {
            @Override
            public void execute(JobExecutionContext context) throws JobExecutionException {
                System.out.println("this is a cron scheduled test job");
            }        
        }
    }
    

    If the above code does not work, try to replace the cronSchedule("0 0 9-12 * * ?") with cronSchedule("0 0 9-12 ? * ?")

    0 讨论(0)
提交回复
热议问题