1. 程式人生 > 程式設計 >springboot定時任務詳解

springboot定時任務詳解

在我們開發專案過程中,經常需要定時任務來幫助我們來做一些內容, Spring Boot 預設已經幫我們實行了,只需要新增相應的註解就可以實現

一、基於註解(靜態)

1、pom 包配置

pom 包裡面只需要引入 Spring Boot Starter 包即可

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

2、建立定時任務實現類

定時任務1:

@Configuration
@EnableScheduling
public class SchedulerTask {

  private int count=0;

  @Scheduled(cron="*/6 * * * * ?")
  private void process(){
    System.out.println("this is scheduler task runing "+(count++));
  }

}

定時任務2:

@Configuration
@EnableScheduling
public class Scheduler2Task {

  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  @Scheduled(fixedRate = 6000)
  public void reportCurrentTime() {
    System.out.println("現在時間:" + dateFormat.format(new Date()));
  }

}

結果如下:

this is scheduler task runing 0
現在時間:09:44:17
this is scheduler task runing 1
現在時間:09:44:23
this is scheduler task runing 2
現在時間:09:44:29
this is scheduler task runing 3
現在時間:09:44:35

引數說明

@Configuration用於標記配置類,兼備Component的效果。

@EnableScheduling表示開啟定時任務

@Scheduled 引數可以接受兩種定時的設定,一種是我們常用的cron="*/6 * * * * ?"

,一種是 fixedRate = 6000,兩種都表示每隔六秒列印一下內容。

fixedRate 說明

@Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行

@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行

@Scheduled(initialDelay=1000,fixedRate=6000) :第一次延遲1秒後執行,之後按 fixedRate 的規則每6秒執行一次

cron屬性,通過表示式形式指定任務執行規則,同樣也是從上一次任務執行完畢開始計時。表示式規則如下:

每個位置的規則如下:

springboot定時任務詳解

備註:

  • 星號(*):可用在所有欄位中,表示對應時間域的每一個時刻,例如,*在分鐘欄位時,表示“每分鐘”。
  • 問號(?):該字元只在日期和星期欄位中使用,它通常指定為“無意義的值”,相當於佔位符。
  • 減號(-):表達一個範圍,如在小時欄位中使用“10-12”,則表示從10到12點,即10,11,12。
  • 逗號(,):表達一個列表值,如在星期欄位中使用“MON,WED,FRI”,則表示星期一,星期三和星期五。
  • 斜槓(/):x/y表達一個等步長序列,x為起始值,y為增量步長值。如在秒數字段中使用0/15,則表示為0,15,30和45秒,而5/15在分鐘欄位中表示5,20,35,50,你也可以使用*/y,它等同於0/y。
  • L:該字元只在日期和星期欄位中使用,代表“Last”的意思,但它在兩個欄位中意思不同。L在日期欄位中,表示這個月份的最後一天,如一月的31號,非閏年二月的28號;如果L用在星期中,則表示星期六,等同於7。但是,如果L出現在星期欄位裡,而且在前面有一個數值X,則表示“這個月的最後X天”,例如,6L表示該月的最後星期五。
  • W:該字元只能出現在日期欄位裡,是對前導日期的修飾,表示離該日期最近的工作日。例如15W表示離該月15號最近的工作日,如果該月15號是星期六,則匹配14號星期五;如果15日是星期日,則匹配16號星期一;如果15號是星期二,那結果就是15號星期二。但必須注意關聯的匹配日期不能夠跨月,如你指定1W,如果1號是星期六,結果匹配的是3號星期一,而非上個月最後的那天。W字串只能指定單一日期,而不能指定日期範圍。
  • LW組合:在日期欄位可以組合使用LW,它的意思是當月的最後一個工作日。
  • 井號(#):該字元只能在星期欄位中使用,表示當月某個工作日。如6#3表示當月的第三個星期五(6表示星期五,#3表示當前的第三個),而4#5表示當月的第五個星期三,假設當月沒有第五個星期三,忽略不觸發。
  • C:該字元只在日期和星期欄位中使用,代表“Calendar”的意思。它的意思是計劃所關聯的日期,如果日期沒有被關聯,則相當於日曆中所有日期。例如5C在日期欄位中就相當於日曆5日以後的第一天。1C在星期欄位中相當於星期日後的第一天。
  • cron表示式對大小寫不敏感。

二、基於介面(動態)

1、pom包配置

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

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.1</version>
</dependency>

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

2、新增資料庫記錄:

開啟本地資料庫mysql,隨便開啟查詢視窗,然後執行指令碼內容,如下:

DROP DATABASE IF EXISTS `socks`;
CREATE DATABASE `socks`;
USE `SOCKS`;
DROP TABLE IF EXISTS `cron`;
CREATE TABLE `cron` (
 `cron_id` varchar(30) NOT NULL PRIMARY KEY,`cron` varchar(30) NOT NULL 
);
INSERT INTO `cron` VALUES ('1','0/5 * * * * ?');

springboot定時任務詳解

然後在application.properties檔案新增資料來源

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/socks?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3、建立定時器

資料庫準備好資料之後,我們編寫定時任務,注意這裡新增的是TriggerTask,目的是迴圈讀取我們在資料庫設定好的執行週期,以及執行相關定時任務的內容。 具體程式碼如下:

package com.cn.service;

import com.cn.dao.CronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Configuration   //1.主要用於標記配置類,兼備Component的效果。
@EnableScheduling  // 2.開啟定時任務
public class DynamicScheduleTask implements SchedulingConfigurer {

  @Autowired
  private CronMapper cronMapper;

  /**
   * 執行定時任務.
   */
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

    taskRegistrar.addTriggerTask(
        //1.新增任務內容(Runnable)
        () -> System.out.println("執行動態定時任務: " + LocalDateTime.now().toLocalTime()),//2.設定執行週期(Trigger)
        triggerContext -> {
          //2.1 從資料庫獲取執行週期
          String cron = cronMapper.selectByPrimaryKey("1").getCron();
          //2.2 合法性校驗.
          if (StringUtils.isEmpty(cron)) {
            // Omitted Code ..
          }
          //2.3 返回執行週期(Date)
          return new CronTrigger(cron).nextExecutionTime(triggerContext);
        }
    );
  }

}

4、啟動測試

然後開啟Navicat ,將執行週期修改為每10秒執行一次,檢視控制檯,發現執行週期已經改變,並且不需要我們重啟應用,十分方便。如圖:

springboot定時任務詳解

三、Quartz

Quartz是OpenSymphony開源組織在Job scheduling領域又一個開源專案,它可以與J2EE與J2SE應用程式相結合也可以單獨使用。Quartz可以用來建立簡單或為執行十個,百個,甚至是好幾萬個Jobs這樣複雜的程式。

1.新增依賴

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

2、編寫任務類

package com.cn.service;
 
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MyQuartz extends QuartzJobBean {
 
  private final Logger log = LoggerFactory.getLogger(MyQuartz.class);
 
  @Override
  protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    log.info("hello quartz");
  }
 
}

3、編寫配置類

package com.cn.config;

import com.cn.service.MyQuartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class QuartzConfig {
 
  @Bean
  public JobDetail myQuartz() {
    return JobBuilder.newJob(MyQuartz.class).withIdentity("MyQuartz").storeDurably().build();
  }
 
  @Bean
  public Trigger studentRankQuartzTrigger() {
    return TriggerBuilder.newTrigger().forJob(myQuartz())
        .withIdentity("MyQuartz")
        .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule().withInterval(5,DateBuilder.IntervalUnit.SECOND))
        .build();
  }
}

4、啟動專案

每隔5秒列印一次"hello quartz"

springboot定時任務詳解

以上就是springboot定時任務詳解的詳細內容,更多關於springboot定時任務的資料請關注我們其它相關文章!