1. 程式人生 > >SpringBoot (九) :定時任務

SpringBoot (九) :定時任務

http 只需要 設置 time() 示例 private his end args

原文出處: 純潔的微笑

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

1、pom包配置

pom包裏面只需要引入springboot 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>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<optional>

true</optional>

</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秒執行一次。

示例代碼

SpringBoot (九) :定時任務