springboot2.x 整合quartz,实现任务的调度

在springboot2.x中已经集成了quartz的starter,咱们只需spring

一、在pom文件中引入数据库

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

二、建立application-quartz.yml文件springboot

文件名以application为前缀,是为了在主配置文件(application.yml)中引入方便app

spring:
  quartz:
    #相关属性配置
    properties:
      org:
        quartz:
          scheduler:
            instanceName: clusteredScheduler
            instanceId: AUTO
          jobStore:
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            tablePrefix: QRTZ_
            isClustered: true
            clusterCheckinInterval: 10000
            useProperties: false
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            threadCount: 10
            threadPriority: 5
            threadsInheritContextClassLoaderOfInitializingThread: true
    #数据库方式
    job-store-type: jdbc
    # 初始化表结构
    # jdbc:
      # initialize-schema: never

三、在主配置文件中引入quartz配置ide

spring: 
  profiles:
    include: quartz

四、建立一个任务控制工具类,用来操做任务spring-boot

因为在springboot 2.x中,已经默认支持了quartz,提供了调度器工厂(SchedulerFactory)和调度器的bean的定义,并经过以上文件配置完成,因此咱们这里直接注入scheduler就能够实现相应的功能。(具体操做略,搜索一下有好多)工具

@Component
public class QuartzManager {
    @Resource
    private Scheduler schedule;

...spa

}继承

五、建立任务类实现Job接口或者继承QuartzJobBean类。接口

此类中就能够注入对应的Service实现具体业务。

六、若是想手动初始化任务,能够建立TaskRunner并实现ApplicationRunner接口,实现run方法来组织定时任务。

@Override
public void run(ApplicationArguments args) throws Exception {
    LOGGER.info("初始化任务");
    String jobName = "abcJob";
    String jobGroup = "DEFAULT";
    String description = "负责清理超时的";
    String jobClassName = "com.xxx.AbcJob";
    String cronExpression = "0 0 0 * * ? *";
    quartzManager.addOrUpdateJob(AbcJob.class, jobName, jobGroup, cronExpression);
}

七、能够使用QuartzManager实现各类任务的动态管理功能

相关文章
相关标签/搜索