一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - springboot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置定時(shí)任務(wù)的方法

springboot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置定時(shí)任務(wù)的方法

2021-01-18 09:27牛奮lch Java教程

本篇文章主要介紹了springboot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置定時(shí)任務(wù)的方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

前言

在我們?nèi)粘5拈_發(fā)中,很多時(shí)候,定時(shí)任務(wù)都不是寫死的,而是寫到數(shù)據(jù)庫中,從而實(shí)現(xiàn)定時(shí)任務(wù)的動(dòng)態(tài)配置,下面就通過一個(gè)簡單的示例,來實(shí)現(xiàn)這個(gè)功能。

一、新建一個(gè)springboot工程,并添加依賴

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
 
    <dependency><!-- 為了方便測試,此處使用了內(nèi)存數(shù)據(jù)庫 -->
      <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對(duì)schedule的支持 -->
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
    </dependency>

二、配置文件application.properties

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 服務(wù)器端口號(hào) 
server.port=7902
# 是否生成ddl語句 
spring.jpa.generate-ddl=false 
# 是否打印sql語句 
spring.jpa.show-sql=true 
# 自動(dòng)生成ddl,由于指定了具體的ddl,此處設(shè)置為none 
spring.jpa.hibernate.ddl-auto=none 
# 使用H2數(shù)據(jù)庫 
spring.datasource.platform=h2 
# 指定生成數(shù)據(jù)庫的schema文件位置 
spring.datasource.schema=classpath:schema.sql 
# 指定插入數(shù)據(jù)庫語句的腳本位置 
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類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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方法……
}

四、任務(wù)類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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配置,所以下面會(huì)以配置Bean的方式來實(shí)現(xiàn)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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:配置定時(shí)任務(wù)
   */
  @Bean(name = "jobDetail")
  public MethodInvokingJobDetailFactoryBean detailFactoryBean(ScheduleTask task) {// ScheduleTask為需要執(zhí)行的任務(wù)
    MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
    /*
     * 是否并發(fā)執(zhí)行
     * 例如每5s執(zhí)行一次任務(wù),但是當(dāng)前任務(wù)還沒有執(zhí)行完,就已經(jīng)過了5s了,
     * 如果此處為true,則下一個(gè)任務(wù)會(huì)執(zhí)行,如果此處為false,則下一個(gè)任務(wù)會(huì)等待上一個(gè)任務(wù)執(zhí)行完后,再開始執(zhí)行
     */
    jobDetail.setConcurrent(false);
     
    jobDetail.setName("srd-chhliu");// 設(shè)置任務(wù)的名字
    jobDetail.setGroup("srd");// 設(shè)置任務(wù)的分組,這些屬性都可以存儲(chǔ)在數(shù)據(jù)庫中,在多任務(wù)的時(shí)候使用
     
    /*
     * 為需要執(zhí)行的實(shí)體類對(duì)應(yīng)的對(duì)象
     */
    jobDetail.setTargetObject(task);
     
    /*
     * sayHello為需要執(zhí)行的方法
     * 通過這幾個(gè)配置,告訴JobDetailFactoryBean我們需要執(zhí)行定時(shí)執(zhí)行ScheduleTask類中的sayHello方法
     */
    jobDetail.setTargetMethod("sayHello");
    return jobDetail;
  }
   
  /**
   * attention:
   * Details:配置定時(shí)任務(wù)的觸發(fā)器,也就是什么時(shí)候觸發(fā)執(zhí)行定時(shí)任務(wù)
   */
  @Bean(name = "jobTrigger")
  public CronTriggerFactoryBean cronJobTrigger(MethodInvokingJobDetailFactoryBean jobDetail) {
    CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
    tigger.setJobDetail(jobDetail.getObject());
    tigger.setCronExpression("0 30 20 * * ?");// 初始時(shí)的cron表達(dá)式
    tigger.setName("srd-chhliu");// trigger的name
    return tigger;
 
  }
 
  /**
   * attention:
   * Details:定義quartz調(diào)度工廠
   */
  @Bean(name = "scheduler")
  public SchedulerFactoryBean schedulerFactory(Trigger cronJobTrigger) {
    SchedulerFactoryBean bean = new SchedulerFactoryBean();
    // 用于quartz集群,QuartzScheduler 啟動(dòng)時(shí)更新己存在的Job
    bean.setOverwriteExistingJobs(true);
    // 延時(shí)啟動(dòng),應(yīng)用啟動(dòng)1秒后
    bean.setStartupDelay(1);
    // 注冊(cè)觸發(fā)器
    bean.setTriggers(cronJobTrigger);
    return bean;
  }
}

六、定時(shí)查庫,并更新任務(wù)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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查庫,并根據(jù)查詢結(jié)果決定是否重新設(shè)置定時(shí)任務(wù)
  public void scheduleUpdateCronTrigger() throws SchedulerException {
    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
    String currentCron = trigger.getCronExpression();// 當(dāng)前Trigger使用的
    String searchCron = repository.findOne(1L).getCron();// 從數(shù)據(jù)庫查詢出來的
    System.out.println(currentCron);
    System.out.println(searchCron);
    if (currentCron.equals(searchCron)) {
      // 如果當(dāng)前使用的cron表達(dá)式和從數(shù)據(jù)庫中查詢出來的cron表達(dá)式一致,則不刷新任務(wù)
    } else {
      // 表達(dá)式調(diào)度構(gòu)建器
      CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
      // 按新的cronExpression表達(dá)式重新構(gòu)建trigger
      trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
      trigger = trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey())
          .withSchedule(scheduleBuilder).build();
      // 按新的trigger重新設(shè)置job執(zhí)行
      scheduler.rescheduleJob(cronTrigger.getKey(), trigger);
      currentCron = searchCron;
    }
  }
}

六、相關(guān)腳本

1、data.sql

?
1
insert into config(id,cron) values(1,'0 0/2 * * * ?'); # 每2分鐘執(zhí)行一次定時(shí)任務(wù)

2、schema.sql

?
1
2
3
4
5
6
drop table config if exists;
create table config(
  id bigint generated by default as identity,
  cron varchar(40),
  primary key(id)
);

六、運(yùn)行測試

測試結(jié)果如下:(Quartz默認(rèn)的線程池大小為10)

?
1
2
3
4
5
6
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!!!

從上面的日志打印時(shí)間來看,我們實(shí)現(xiàn)了動(dòng)態(tài)配置,最初的時(shí)候,任務(wù)是每天20:30執(zhí)行,后面通過動(dòng)態(tài)刷新變成了每隔2分鐘執(zhí)行一次。

雖然上面的解決方案沒有使用Quartz推薦的方式完美,但基本上可以滿足我們的需求,當(dāng)然也可以采用觸發(fā)事件的方式來實(shí)現(xiàn),例如當(dāng)前端修改定時(shí)任務(wù)的觸發(fā)時(shí)間時(shí),異步的向后臺(tái)發(fā)送通知,后臺(tái)收到通知后,然后再更新程序,也可以實(shí)現(xiàn)動(dòng)態(tài)的定時(shí)任務(wù)刷新

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/liuchuanhong1/article/details/60873295

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品青青在线观看香蕉 | 亚洲午夜精品久久久久久抢 | 国产真实伦对白在线播放 | 精品久久久久免费极品大片 | 久久性综合亚洲精品电影网 | 亚洲春色综合另类网蜜桃 | 欧美香蕉人人人人人人爱 | 情乱奶水欲 | 亚洲品质自拍视频网站 | 亚洲不卡视频 | 涩涩屋在线播放 | 国产精品 视频一区 二区三区 | 欧美日韩国产亚洲一区二区 | 欧美日韩视频在线第一区二区三区 | 继的朋友无遮漫画免费观看73 | 手机免费在线视频 | 日本又黄又裸一级大黄裸片 | 成人观看免费大片在线观看 | 荡女人人爱全文免费阅读 | 久久99re热在线观看视频 | 亚洲一区二区三区福利在线 | 午夜办公室在线观看高清电影 | 香蕉久久一区二区三区啪啪 | 99pao在线视频精品免费 | 激情亚洲| 免费一级特黄特色大片 | 91精品国产综合久久消防器材 | 日本激情网站 | 国产自拍视频网站 | 秋葵丝瓜茄子草莓榴莲樱桃 | 久久婷婷五月免费综合色啪 | 日韩欧美色图 | 欧美日韩国产精品综合 | 教师波多野结衣在线播放 | 极品美女穴 | 男人与雌性宠物交啪啪小说 | 教室里老师好紧h | 国产第一草草影院 | 国产欧美精品一区二区三区–老狼 | 果冻传媒在线观看的 | 好爽好粗 |