1. 程式人生 > >Spring Boot (教程十三:定時任務)

Spring Boot (教程十三:定時任務)

GitHub 地址:

建立Spring Boot 基礎工程

  • pom.xml
<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>

啟動類開啟定時排程器

  • SpringbootHelloApplication.java
@SpringBootApplication
@EnableScheduling   //開啟定時器
public class SpringbootHelloApplication {
public static void main(String[] args) {
        SpringApplication.run(SpringbootHelloApplication.class, args);
    }
}

建立定時器

  • SchedulerTask1.java

包所在:com.example.task

package com.example.task;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class SchedulerTask1 {
    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Scheduled(cron="*/5 * * * * ?")
    public void dateTask(){
        LOG.info("SchedulerTask1 : " + new Date().toString());
    }
}


啟動工程之後,5秒列印一段時間。

1

  • SchedulerTask2.java

包所在:com.example.task

package com.example.task;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerTask2 {
    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Scheduled(fixedRate = 5000)
    private void dateTask() {
        LOG.info("SchedulerTask2 : " + new Date().toString());
    }
}


啟動工程之後,5秒列印一段時間。

2

引數說明


@Scheduled 註解

  • @Scheduled 註解可以接受兩種定時的設定,一種是我們常用的cron="*/5 * * * * ?" ,一種是 fixedRate=5000,兩種都表示每隔五秒列印一下內容。

cron 引數


一個cron表示式有至少6個(也可能7個)有空格分隔的時間元素。按順序依次為

  • 秒(0~59)
  • 分鐘(0~59)
  • 小時(0~23)
  • 天(月)(0~31,但是你需要考慮你月的天數)
  • 月(0~11)
  • 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
  • 7.年份(1970-2099)

fixedRate 引數

  • @Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行

  • @Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行

  • @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次