SpringBoot中定時任務的設置


1.注解:@EnableScheduling  用在SpringBoot項目中的啟動類上,表示開啟對定時任務的支持;@PropertySource(value = {"file:application.properties"})  讀取指定的外部配置,和jar包同級目錄;

package com.datacollector;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@SpringBootApplication
@EnableScheduling
@PropertySource(value = {"file:application.properties"})
public class DataCollectorApplication {

    public static void main(String[] args) {
        SpringApplication.run(DataCollectorApplication.class, args);
    }
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();

    }


}

2.注解:@Scheduled  中有以下幾個參數:

  1>.cron是設置定時執行的表達式,如 0 0/5 * * * ?每隔五分鍾執行一次 秒 分 時 天 月

每隔5秒執行一次:"*/5 * * * * ?"

每隔1分鍾執行一次:"0 */1 * * * ?"

每天23點執行一次:"0 0 23 * * ?"

每天凌晨1點執行一次:"0 0 1 * * ?"

每月1號凌晨1點執行一次:"0 0 1 1 * ?"

每月最后一天23點執行一次:"0 0 23 L * ?"

每周星期天凌晨1點實行一次:"0 0 1 ? * L"

在26分、29分、33分執行一次:"0 26,29,33 * * * ?"

每天的0點、13點、18點、21點都執行一次:"0 0 0,13,18,21 * * ?"

表示在每月的1日的凌晨2點調度任務:"0 0 2 1 * ? *"

表示周一到周五每天上午10:15執行作業:"0 15 10 ? * MON-FRI" 

表示2002-2006年的每個月的最后一個星期五上午10:15執行:"0 15 10 ? 6L 2002-2006"

  2>.zone表示執行時間的時區

  3>.fixedDelay 和fixedDelayString 表示一個固定延遲時間執行,上個任務完成后,延遲多長時間執行

  4>.fixedRate 和fixedRateString表示一個固定頻率執行,上個任務開始后,多長時間后開始執行

  5>.initialDelay 和initialDelayString表示一個初始延遲時間,第一次被調用前延遲的時間

注:這里詳細說明一下 fixedRate  和 fixedRateString 的區別,fixedRate  =[final 修飾的一個常量];fixedRateString =[一個字符串];當考慮時間可以在項目中自定義設置,我們一般會采取讀配置文件來獲取設置的時間

具體實現代碼如下:

1.fixedRate 沒有辦法使用外部配置注入時間

//@value("${TIME}") 是無效的
private final int TIME=6000;
    
    @Scheduled(fixedRate = TIME)
    public void testScheduledUsed(){
        System.out.println("這是一個定時任務");
    }

2.fixedRateString 可以使用外部配置注入時間

    @Scheduled(fixedRateString = "${TIME}")
    public void testScheduledUsed(){
        System.out.println("這是一個定時任務");
    }

配置文件  application.properties 

TIME=5000


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM