SpringBoot第十七篇:定時任務

做者:追夢1819
原文:https://www.cnblogs.com/yanfei1819/p/11076555.html
版權聲明:本文爲博主原創文章,轉載請附上博文連接!

html

引言

  相信你們對定時任務很熟悉,其重要性也不言而喻。定時發短信、定時批量操做、定時統計數據等,都離不開定時任務。本文將講解定時任務在 SpringBoot 項目中的應用。java


版本信息

  • JDK:1.8
  • SpringBoot :2.0.1.RELEASE
  • maven:3.3.9
  • IDEA:2019.1.1
  • quartz:2.3.0


定時任務實現方式

JDK自帶的Timer

  Timer 是Java 自帶的定時任務類。能夠用做比較簡單的定時任務。一般用的很少。下面以一個小的示例展現其用法。spring


SpringBoot集成的schedule

這種方式是 SpringBoot 集成的,使用很簡單。springboot

首先,引入 SpringBoot 的基礎 jar:app

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


而後再啓動類中添加註解 @EnableScheduling 便可開啓 SpringBoot 定時任務:框架

@SpringBootApplication
@EnableScheduling
public class TimedTaskDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TimedTaskDemoApplication.class, args);
    }
}


下面根據 @Scheduled 的不一樣屬性建立幾個任務:maven

任務一:ide

@Component
public class FirstTask {
    /**
     * cron 表達式
     */
//    @Scheduled(cron = "0/2 * * * * *")
    @Scheduled(cron="${cron.schedule}")
    public void run(){
        System.out.println("這是建立的第一個定時任務");
    }
}

做幾點說明:spring-boot

  1. cron 表達式是 @Scheduled 的屬性之一,其值能夠直接設置爲 cron 表達式;
  2. @Scheduled(cron="${cron.schedule}") 是動態讀取 application.properties 配置文件中的 cron 表達式。例如項目中的一個需求是天天凌晨0點執行,可是對於測試人員來講,不可能等到凌晨測試。動態讀取能夠幫助解決該問題。

任務二:測試

@Component
public class SecondTask {
    /**
     * 上一次執行完畢時間點以後多長時間再執行(ms)
     */
    @Scheduled(fixedDelay = 2000)
    public void run(){
        System.out.println("這是建立的第二個定時任務");
    }
}


任務三:

@Component
public class ThirdTask {
    /**
     * 與fixedDelay功能相同,上一次執行完畢時間點以後多長時間再執行(ms),區別是:一、時間是字符串;二、支持佔位符
     */
    // @Scheduled(fixedDelayString = "2000")
    @Scheduled(fixedDelayString = "${time.fixedDelay}")
    public void run(){
        System.out.println("這是建立的第三個定時任務");
    }
}


上面的三個任務列舉了 @Scheduled 註解的三個參數。其實除此以外,查看 @Scheduled 的源碼可知,還有其他的幾個參數:

  • fixedRate:上一次開始執行時間點以後多長時間再執行;
  • fixedRateString:上一次開始執行時間點以後多長時間再執行;
  • fixedRateString:與fixedRate 意思相同,只是使用字符串的形式。惟一不一樣的是支持佔位符;
  • initialDelay:第一次延遲多長時間後再執行;
  • initialDelayString:與 initialDelay 意思相同,只是使用字符串的形式。惟一不一樣的是支持佔位符;


整合Quartz

  若是以上的方式都沒法知足項目的需求,則能夠試試 Quartz 調度框架。它功能的強大以及使用無需多說了。此處咱們看看 Quartz 在 SpringBoot 中的使用。

建立項目,引入 Quartz 調度框架啓動器:

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


  須要注意版本信息,若是 SpringBoot 版本是2.0之後的版本,直接引入 Quartz 啓動器便可。可是若是是2.0之前的版本,須要引入如下 jar 包:

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>


下面建立任務了:

public class QuartzTask extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println(new Date());
    }
}

任務須要繼承 QuartzJobBean 抽象類,並重寫 executeInternal 方法。


第三步,建立 quartz 配置類,添加 @Configuration 註解:

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail testQuartzTask() {
        return JobBuilder.newJob(QuartzTask.class).withIdentity("quartztask").storeDurably().build();
    }
    @Bean
    public Trigger testQuartzTrigger2() {
        //cron方式,每隔5秒執行一次
        return TriggerBuilder.newTrigger().forJob(testQuartzTask())
                .withIdentity("quartztask")
                .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?"))
                .build();
    }
}

  上面的示例是使用 cron 表達式,固然也能夠是固定時間間隔。本節是闡述 SpringBoot 和 Quartz 的整合,不做 Quartz 的詳細使用。感興趣的讀者能夠登陸 Quartz 的官網 或者中文官網自行研究。


總結

  定時任務的實現方式有不少種,除了上面說到的幾種方式,還有利用線程池實現定時任務,有的系統是經過 Liunx 實現定時任務。總之,定時任務的實現方式多種多樣,其方式要根據項目的實際狀況而選。切不可爲了實現而實現。



相關文章
相關標籤/搜索