SpringBoot整合Quartz

1.引入quzrtz

<dependency>  
            <groupId>org.quartz-scheduler</groupId>  
            <artifactId>quartz</artifactId>  
            <version>2.2.1</version>  
            <exclusions>  
                <exclusion>  
                    <artifactId>slf4j-api</artifactId>  
                    <groupId>org.slf4j</groupId>  
                </exclusion>  
            </exclusions>  
        </dependency>

2.新建1个类,模拟定时任务

ScheduledJob.java

public class ScheduledJob implements Job{     
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException { 
        System.out.println("第一个定时任务" + new Date()); 
    } 
}

3.新建类MyScheduler

package com.abc.data.jobs;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

@Component
public class MyScheduler {
    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    static Scheduler scheduler;

    public void scheduleJobs() throws SchedulerException {
        scheduler = schedulerFactoryBean.getScheduler();
        startJob1();
    }

    public static void startJob1() throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(DataSyncJob.class).withIdentity("job1", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/2 * * * * ?");
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}

3.添加SchedulerListener.java,必须有@Configuration注解

package com.abc.data.jobs;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class SchedulerListener  implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    public MyScheduler myScheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            myScheduler.scheduleJobs();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        return schedulerFactoryBean;
    }
}

 

5.启动springboot 即可看到效果  2秒/次

参考 https://www.kancloud.cn/fymod/springcloud/536929

posted @ 2018-06-01 13:31  甜菜波波  阅读(2617)  评论(0编辑  收藏  举报