Spring Boot(九):定時任務


在我們開發項目過程中,經常需要定時任務來幫助我們來做一些內容, Spring Boot 默認已經幫我們實行了,只需要添加相應的注解就可以實現

1、pom 包配置

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

<dependencies>
	<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>
</dependencies>

2、啟動類啟用定時

在啟動類上面加上@EnableScheduling即可開啟定時

@SpringBootApplication
@EnableScheduling
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

3、創建定時任務實現類

定時任務1:

@Component
public class SchedulerTask {

    private int count=0;

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

}

定時任務2:

@Component
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

參數說明

@Scheduled 參數可以接受兩種定時的設置,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內容。

fixedRate 說明

  • @Scheduled(fixedRate = 6000) :上一次開始執行時間點之后6秒再執行
  • @Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之后6秒再執行
  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執行,之后按 fixedRate 的規則每6秒執行一次

文章內容已經升級到 Spring Boot 2.x

示例代碼-github

示例代碼-碼雲


免責聲明!

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



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