1. 程式人生 > >SpringBoot 學習系列(五)

SpringBoot 學習系列(五)

SpringBoot可以讓我們快速的開發一個定時任務程式。

在我們的專案開發過程中,經常需要定時任務來幫助我們來做一些內容,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秒執行一次