以Springboot为例介绍通过Quartz作业调度框架实现定时任务。

1、引用Quartz依赖

<!--引入Quartz-->
<dependency>
     <groupId>org.quartz-scheduler</groupId>
     <artifactId>quartz</artifactId>
     <version>2.3.2</version>
</dependency>

2、实现具体的可执行的调度任务类,调度任务类需实现Quartz框架提供的Job接口。

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    //获取JobDetail中的JobDataMap
    JobDataMap jobDetailMap = jobExecutionContext.getJobDetail().getJobDataMap();
    for(Entry<String, Object> objectEntry: jobDetailMap.entrySet()){
        System.out.println("jobDetailMap---"+objectEntry.getKey()+" "+objectEntry.getValue());
    }
    //获取trigger中的JobDataMap
    JobDataMap triggerMap = jobExecutionContext.getTrigger().getJobDataMap();
    for(Entry<String, Object> objectEntry: triggerMap.entrySet()){
        System.out.println("triggerMap---"+objectEntry.getKey()+" "+objectEntry.getValue());
    }
    //获取trigger和JobDetail中的JobDataMap总和,如果有同一个key,则后者会将前者覆盖
    JobDataMap allMap = jobExecutionContext.getMergedJobDataMap();
    for(Entry<String, Object> objectEntry: allMap.entrySet()){
        System.out.println("allMap"+objectEntry.getKey()+" "+objectEntry.getValue());
    }
}

  

3、实现任务调度逻辑,使用@PostConstruct使此定时任务在项目启动时即开始运行。

@PostConstruct
public void buildQuartz(){

    JobBuilder jobBuilder = JobBuilder.newJob(QuartzService.class).withIdentity(jobName,jobGroupName);
    jobBuilder.usingJobData("jobDetail参数","jobDetail值");

    JobDetail jobDetail = jobBuilder.build();

    /*
    * 按照指定间隔时间执行
    * startNow()马上执行
    * withIntervalInSeconds(1) 按秒循环,1s循环一次
    * repeatForever() 永远循环
    * */
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName,triggerGroupName)
        .startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
        .build();

    //表达式调度构建器
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/3 * * * * ? *")
        .withMisfireHandlingInstructionDoNothing();

    /*
     *  按照cron格式 定时执行
     * */
    Trigger triggerCron = TriggerBuilder.newTrigger().withIdentity(triggerName,triggerGroupName)
        .startNow().withSchedule(scheduleBuilder).usingJobData("trigger参数","trigger值")
        .build();

    SchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
    Scheduler scheduler = null;
    try {
        scheduler = stdSchedulerFactory.getScheduler();
        scheduler.scheduleJob(jobDetail,triggerCron);
        scheduler.start();
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}