当前位置: 移动技术网 > IT编程>开发语言>Java > springboot整合Quartz实现动态配置定时任务的方法

springboot整合Quartz实现动态配置定时任务的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

在我们日常的开发中,很多时候,定时任务都不是写死的,而是写到数据库中,从而实现定时任务的动态配置,下面就通过一个简单的示例,来实现这个功能。

一、新建一个springboot工程,并添加依赖

<dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter-data-jpa</artifactid> 
    </dependency> 
 
    <dependency><!-- 为了方便测试,此处使用了内存数据库 --> 
      <groupid>com.h2database</groupid> 
      <artifactid>h2</artifactid> 
      <scope>runtime</scope> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter-test</artifactid> 
      <scope>test</scope> 
    </dependency> 
     
    <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> 
    <dependency><!-- 该依赖必加,里面有sping对schedule的支持 --> 
            <groupid>org.springframework</groupid> 
            <artifactid>spring-context-support</artifactid> 
    </dependency> 

二、配置文件application.properties

# 服务器端口号  
server.port=7902 
# 是否生成ddl语句  
spring.jpa.generate-ddl=false  
# 是否打印sql语句  
spring.jpa.show-sql=true  
# 自动生成ddl,由于指定了具体的ddl,此处设置为none  
spring.jpa.hibernate.ddl-auto=none  
# 使用h2数据库  
spring.datasource.platform=h2  
# 指定生成数据库的schema文件位置  
spring.datasource.schema=classpath:schema.sql  
# 指定插入数据库语句的脚本位置  
spring.datasource.data=classpath:data.sql  
# 配置日志打印信息  
logging.level.root=info  
logging.level.org.hibernate=info  
logging.level.org.hibernate.type.descriptor.sql.basicbinder=trace  
logging.level.org.hibernate.type.descriptor.sql.basicextractor=trace  
logging.level.com.itmuch=debug  

三、entity类

package com.chhliu.springboot.quartz.entity; 
 
import javax.persistence.column; 
import javax.persistence.entity; 
import javax.persistence.generatedvalue; 
import javax.persistence.generationtype; 
import javax.persistence.id; 
 
@entity 
public class config { 
  @id 
   @generatedvalue(strategy = generationtype.auto) 
   private long id; 
 
   @column 
   private string cron; 
 
  /** 
   * @return the id 
   */ 
  public long getid() { 
    return id; 
  } 
    ……此处省略getter和setter方法…… 
} 

四、任务类

package com.chhliu.springboot.quartz.entity; 
 
import org.slf4j.logger; 
import org.slf4j.loggerfactory; 
import org.springframework.context.annotation.configuration; 
import org.springframework.scheduling.annotation.enablescheduling; 
import org.springframework.stereotype.component; 
 
@configuration 
@component // 此注解必加 
@enablescheduling // 此注解必加 
public class scheduletask { 
  private static final logger logger = loggerfactory.getlogger(scheduletask.class); 
  public void sayhello(){ 
    logger.info("hello world, i'm the king of the world!!!"); 
  } 
} 

五、quartz配置类

由于springboot追求零xml配置,所以下面会以配置bean的方式来实现

package com.chhliu.springboot.quartz.entity; 
 
import org.quartz.trigger; 
import org.springframework.context.annotation.bean; 
import org.springframework.context.annotation.configuration; 
import org.springframework.scheduling.quartz.crontriggerfactorybean; 
import org.springframework.scheduling.quartz.methodinvokingjobdetailfactorybean; 
import org.springframework.scheduling.quartz.schedulerfactorybean; 
 
@configuration 
public class quartzconfigration { 
  /** 
   * attention: 
   * details:配置定时任务 
   */ 
  @bean(name = "jobdetail") 
  public methodinvokingjobdetailfactorybean detailfactorybean(scheduletask task) {// scheduletask为需要执行的任务 
    methodinvokingjobdetailfactorybean jobdetail = new methodinvokingjobdetailfactorybean(); 
    /* 
     * 是否并发执行 
     * 例如每5s执行一次任务,但是当前任务还没有执行完,就已经过了5s了, 
     * 如果此处为true,则下一个任务会执行,如果此处为false,则下一个任务会等待上一个任务执行完后,再开始执行 
     */ 
    jobdetail.setconcurrent(false); 
     
    jobdetail.setname("srd-chhliu");// 设置任务的名字 
    jobdetail.setgroup("srd");// 设置任务的分组,这些属性都可以存储在数据库中,在多任务的时候使用 
     
    /* 
     * 为需要执行的实体类对应的对象 
     */ 
    jobdetail.settargetobject(task); 
     
    /* 
     * sayhello为需要执行的方法 
     * 通过这几个配置,告诉jobdetailfactorybean我们需要执行定时执行scheduletask类中的sayhello方法 
     */ 
    jobdetail.settargetmethod("sayhello"); 
    return jobdetail; 
  } 
   
  /** 
   * attention: 
   * details:配置定时任务的触发器,也就是什么时候触发执行定时任务 
   */ 
  @bean(name = "jobtrigger") 
  public crontriggerfactorybean cronjobtrigger(methodinvokingjobdetailfactorybean jobdetail) { 
    crontriggerfactorybean tigger = new crontriggerfactorybean(); 
    tigger.setjobdetail(jobdetail.getobject()); 
    tigger.setcronexpression("0 30 20 * * ?");// 初始时的cron表达式 
    tigger.setname("srd-chhliu");// trigger的name 
    return tigger; 
 
  } 
 
  /** 
   * attention: 
   * details:定义quartz调度工厂 
   */ 
  @bean(name = "scheduler") 
  public schedulerfactorybean schedulerfactory(trigger cronjobtrigger) { 
    schedulerfactorybean bean = new schedulerfactorybean(); 
    // 用于quartz集群,quartzscheduler 启动时更新己存在的job 
    bean.setoverwriteexistingjobs(true); 
    // 延时启动,应用启动1秒后 
    bean.setstartupdelay(1); 
    // 注册触发器 
    bean.settriggers(cronjobtrigger); 
    return bean; 
  } 
} 

六、定时查库,并更新任务

package com.chhliu.springboot.quartz.entity; 
 
import javax.annotation.resource; 
 
import org.quartz.cronschedulebuilder; 
import org.quartz.crontrigger; 
import org.quartz.jobdetail; 
import org.quartz.scheduler; 
import org.quartz.schedulerexception; 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.context.annotation.configuration; 
import org.springframework.scheduling.annotation.enablescheduling; 
import org.springframework.scheduling.annotation.scheduled; 
import org.springframework.stereotype.component; 
 
import com.chhliu.springboot.quartz.repository.configrepository; 
 
@configuration 
@enablescheduling 
@component 
public class schedulerefreshdatabase { 
  @autowired 
  private configrepository repository; 
 
  @resource(name = "jobdetail") 
  private jobdetail jobdetail; 
 
  @resource(name = "jobtrigger") 
  private crontrigger crontrigger; 
 
  @resource(name = "scheduler") 
  private scheduler scheduler; 
 
  @scheduled(fixedrate = 5000) // 每隔5s查库,并根据查询结果决定是否重新设置定时任务 
  public void scheduleupdatecrontrigger() throws schedulerexception { 
    crontrigger trigger = (crontrigger) scheduler.gettrigger(crontrigger.getkey()); 
    string currentcron = trigger.getcronexpression();// 当前trigger使用的 
    string searchcron = repository.findone(1l).getcron();// 从数据库查询出来的 
    system.out.println(currentcron); 
    system.out.println(searchcron); 
    if (currentcron.equals(searchcron)) { 
      // 如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致,则不刷新任务 
    } else { 
      // 表达式调度构建器 
      cronschedulebuilder schedulebuilder = cronschedulebuilder.cronschedule(searchcron); 
      // 按新的cronexpression表达式重新构建trigger 
      trigger = (crontrigger) scheduler.gettrigger(crontrigger.getkey()); 
      trigger = trigger.gettriggerbuilder().withidentity(crontrigger.getkey()) 
          .withschedule(schedulebuilder).build(); 
      // 按新的trigger重新设置job执行 
      scheduler.reschedulejob(crontrigger.getkey(), trigger); 
      currentcron = searchcron; 
    } 
  } 
} 

六、相关脚本

1、data.sql

insert into config(id,cron) values(1,'0 0/2 * * * ?'); # 每2分钟执行一次定时任务

2、schema.sql

drop table config if exists; 
create table config( 
  id bigint generated by default as identity, 
  cron varchar(40), 
  primary key(id) 
); 

六、运行测试

测试结果如下:(quartz默认的线程池大小为10)

0 30 20 * * ? 
0 0/2 * * * ? 
2017-03-08 18:02:00.025 info 5328 --- [eduler_worker-1] c.c.s.quartz.entity.scheduletask     : hello world, i'm the king of the world!!! 
2017-03-08 18:04:00.003 info 5328 --- [eduler_worker-2] c.c.s.quartz.entity.scheduletask     : hello world, i'm the king of the world!!! 
2017-03-08 18:06:00.002 info 5328 --- [eduler_worker-3] c.c.s.quartz.entity.scheduletask     : hello world, i'm the king of the world!!! 
2017-03-08 18:08:00.002 info 5328 --- [eduler_worker-4] c.c.s.quartz.entity.scheduletask     : hello world, i'm the king of the world!!! 

从上面的日志打印时间来看,我们实现了动态配置,最初的时候,任务是每天20:30执行,后面通过动态刷新变成了每隔2分钟执行一次。

虽然上面的解决方案没有使用quartz推荐的方式完美,但基本上可以满足我们的需求,当然也可以采用触发事件的方式来实现,例如当前端修改定时任务的触发时间时,异步的向后台发送通知,后台收到通知后,然后再更新程序,也可以实现动态的定时任务刷新

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网