1. 程式人生 > >SpringBoot實現定時任務

SpringBoot實現定時任務

文章目錄


開發環境

  • JDK 1.8
  • springboot版本 1.5.12
    springboot實現定時任務相當簡單, 只需兩步.

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.thc</groupId> <artifactId>springboot-04-task</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</
packaging
>
<name>springboot-06-task</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.RELEASE</
version
>
<relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

主啟動類

在啟動類加上如下的註解
@EnableScheduling 表示開啟基於註解的定時任務

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

//開啟基於註解的定時任務
@EnableScheduling 
@SpringBootApplication
public class Springboot04TaskApplication {

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

在service類寫定時任務的方法

在方法上加上@Scheduled ,表示這是一個定時任務的方法.
後面寫上定時任務的表示式.
關於定時任務的表示式,可以看我另一篇文章.
https://blog.csdn.net/qq_33229669/article/details/85013881
也可以在如下的網頁中,進行定時任務的線上生成. 要去掉最後一位年. 因為spring的cron表示式,只支援 秒分時日月星期, 六位. 如果是七位會報錯
http://cron.qqe2.com/

@Service
public class ScheduledService {
	@Scheduled(cron = "* * * * * ?")
    public void hello(){
        System.out.println("hello ... ");
    }
}

啟動工程後,效果如下圖