乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

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

       WindySky 2017-10-10

      前言

      在我們?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. <dependency>  
      2.             <groupId>org.springframework.boot</groupId>  
      3.             <artifactId>spring-boot-starter-data-jpa</artifactId>  
      4.         </dependency>  
      5.   
      6.         <dependency><!-- 為了方便測試,此處使用了內(nèi)存數(shù)據(jù)庫 -->  
      7.             <groupId>com.h2database</groupId>  
      8.             <artifactId>h2</artifactId>  
      9.             <scope>runtime</scope>  
      10.         </dependency>  
      11.         <dependency>  
      12.             <groupId>org.springframework.boot</groupId>  
      13.             <artifactId>spring-boot-starter-test</artifactId>  
      14.             <scope>test</scope>  
      15.         </dependency>  
      16.           
      17.         <dependency>  
      18.             <groupId>org.quartz-scheduler</groupId>  
      19.             <artifactId>quartz</artifactId>  
      20.             <version>2.2.1</version>  
      21.             <exclusions>  
      22.                 <exclusion>  
      23.                     <artifactId>slf4j-api</artifactId>  
      24.                     <groupId>org.slf4j</groupId>  
      25.                 </exclusion>  
      26.             </exclusions>  
      27.         </dependency>  
      28.         <dependency><!-- 該依賴必加,里面有sping對(duì)schedule的支持 -->  
      29.                        <groupId>org.springframework</groupId>  
      30.                        <artifactId>spring-context-support</artifactId>  
      31.         </dependency>  
      二、配置文件application.properties

      1. # 服務(wù)器端口號(hào)    
      2. server.port=7902  
      3. # 是否生成ddl語句    
      4. spring.jpa.generate-ddl=false    
      5. # 是否打印sql語句    
      6. spring.jpa.show-sql=true    
      7. # 自動(dòng)生成ddl,由于指定了具體的ddl,此處設(shè)置為none    
      8. spring.jpa.hibernate.ddl-auto=none    
      9. # 使用H2數(shù)據(jù)庫    
      10. spring.datasource.platform=h2    
      11. # 指定生成數(shù)據(jù)庫的schema文件位置    
      12. spring.datasource.schema=classpath:schema.sql    
      13. # 指定插入數(shù)據(jù)庫語句的腳本位置    
      14. spring.datasource.data=classpath:data.sql    
      15. # 配置日志打印信息    
      16. logging.level.root=INFO    
      17. logging.level.org.hibernate=INFO    
      18. logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE    
      19. logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE    
      20. logging.level.com.itmuch=DEBUG   
      三、Entity類

      1. package com.chhliu.springboot.quartz.entity;  
      2.   
      3. import javax.persistence.Column;  
      4. import javax.persistence.Entity;  
      5. import javax.persistence.GeneratedValue;  
      6. import javax.persistence.GenerationType;  
      7. import javax.persistence.Id;  
      8.   
      9. @Entity  
      10. public class Config {  
      11.     @Id  
      12.       @GeneratedValue(strategy = GenerationType.AUTO)  
      13.       private Long id;  
      14.   
      15.       @Column  
      16.       private String cron;  
      17.   
      18.     /** 
      19.      * @return the id 
      20.      */  
      21.     public Long getId() {  
      22.         return id;  
      23.     }  
      24.         ……此處省略getter和setter方法……  
      25. }  
      四、任務(wù)類

      1. package com.chhliu.springboot.quartz.entity;  
      2.   
      3. import org.slf4j.Logger;  
      4. import org.slf4j.LoggerFactory;  
      5. import org.springframework.context.annotation.Configuration;  
      6. import org.springframework.scheduling.annotation.EnableScheduling;  
      7. import org.springframework.stereotype.Component;  
      8.   
      9. @Configuration  
      10. @Component // 此注解必加  
      11. @EnableScheduling // 此注解必加  
      12. public class ScheduleTask {  
      13.     private static final Logger LOGGER =  LoggerFactory.getLogger(ScheduleTask.class);  
      14.     public void sayHello(){  
      15.         LOGGER.info("Hello world, i'm the king of the world!!!");  
      16.     }  
      17. }  
      五、Quartz配置類

      由于springboot追求零xml配置,所以下面會(huì)以配置Bean的方式來實(shí)現(xiàn)

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

      1. package com.chhliu.springboot.quartz.entity;  
      2.   
      3. import javax.annotation.Resource;  
      4.   
      5. import org.quartz.CronScheduleBuilder;  
      6. import org.quartz.CronTrigger;  
      7. import org.quartz.JobDetail;  
      8. import org.quartz.Scheduler;  
      9. import org.quartz.SchedulerException;  
      10. import org.springframework.beans.factory.annotation.Autowired;  
      11. import org.springframework.context.annotation.Configuration;  
      12. import org.springframework.scheduling.annotation.EnableScheduling;  
      13. import org.springframework.scheduling.annotation.Scheduled;  
      14. import org.springframework.stereotype.Component;  
      15.   
      16. import com.chhliu.springboot.quartz.repository.ConfigRepository;  
      17.   
      18. @Configuration  
      19. @EnableScheduling  
      20. @Component  
      21. public class ScheduleRefreshDatabase {  
      22.     @Autowired  
      23.     private ConfigRepository repository;  
      24.   
      25.     @Resource(name = "jobDetail")  
      26.     private JobDetail jobDetail;  
      27.   
      28.     @Resource(name = "jobTrigger")  
      29.     private CronTrigger cronTrigger;  
      30.   
      31.     @Resource(name = "scheduler")  
      32.     private Scheduler scheduler;  
      33.   
      34.     @Scheduled(fixedRate = 5000) // 每隔5s查庫,并根據(jù)查詢結(jié)果決定是否重新設(shè)置定時(shí)任務(wù)  
      35.     public void scheduleUpdateCronTrigger() throws SchedulerException {  
      36.         CronTrigger trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());  
      37.         String currentCron = trigger.getCronExpression();// 當(dāng)前Trigger使用的  
      38.         String searchCron = repository.findOne(1L).getCron();// 從數(shù)據(jù)庫查詢出來的  
      39.         System.out.println(currentCron);  
      40.         System.out.println(searchCron);  
      41.         if (currentCron.equals(searchCron)) {  
      42.             // 如果當(dāng)前使用的cron表達(dá)式和從數(shù)據(jù)庫中查詢出來的cron表達(dá)式一致,則不刷新任務(wù)  
      43.         } else {  
      44.             // 表達(dá)式調(diào)度構(gòu)建器  
      45.             CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);  
      46.             // 按新的cronExpression表達(dá)式重新構(gòu)建trigger  
      47.             trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());  
      48.             trigger = trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey())  
      49.                     .withSchedule(scheduleBuilder).build();  
      50.             // 按新的trigger重新設(shè)置job執(zhí)行  
      51.             scheduler.rescheduleJob(cronTrigger.getKey(), trigger);  
      52.             currentCron = searchCron;  
      53.         }  
      54.     }  
      55. }  
      六、相關(guān)腳本

      1、data.sql

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

      1. drop table config if exists;  
      2. create table config(  
      3.     id bigint generated by default as identity,  
      4.     cron varchar(40),  
      5.     primary key(id)  
      6. );  
      六、運(yùn)行測試

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

      1. 0 30 20 * * ?  
      2. 0 0/2 * * * ?  
      3. 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!!!  
      4. 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!!!  
      5. 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!!!  
      6. 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ù)刷新

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多