1. 程式人生 > >Spring Boot中使用@Scheduled建立定時任務實戰

Spring Boot中使用@Scheduled建立定時任務實戰

一 點睛

我們在編寫Spring Boot應用中經常會遇到這樣的場景,比如:我需要定時地傳送一些簡訊、郵件之類的操作,也可能會定時地檢查和監控一些標誌、引數等。此時,定時任務就派上用場了。

@Scheduled詳解

對於@Scheduled的使用可以總結如下幾種方式:

  • @Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行
  • @Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行
  • @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
  • @Scheduled(cron="*/5 * * * * *") :通過cron表示式定義規則

二 實戰

1 新建依賴

<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 定時任務實現類

package com.didispace.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ScheduledTasks {

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

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

}

3 啟動類

package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
//開啟定時任務功能
@EnableScheduling
public class Application {

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

}

三 執行結果

當前時間:09:11:48

當前時間:09:11:53

當前時間:09:11:58

四 參考