SpringBoot @Scheduled 定時任務 入門demo
阿新 • • 發佈:2018-11-05
專案結果:
1、 專案所需的jar包,因為是SpringBoot的demo,所以這裡只需要引入spring-boot-starter-parent和spring-boot-starter-web即可。
pom.xml:
<?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.springboot</groupId> <artifactId>scheduled-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>scheduled-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.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-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>
1、啟動類:加上@EnableScheduling,這樣才會去掃描@Scheduled的方法,去掉之後@Scheduled的方法將不會被執行。
package com.springboot.scheduleddemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class ScheduledDemoApplication { public static void main(String[] args) { SpringApplication.run(ScheduledDemoApplication.class, args); } }
2、寫定時任務:
參考:線上Cron表示式
@Scheduled() 註解中寫入Cron表示式。
此處將類加上@Component註解或者@Service均可。
"0/1 * * * * ? "表示每秒執行一次
package com.springboot.scheduleddemo.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; /** * @author: Lucifer * @create: 2018-10-29 22:39 * @description: **/ @Component public class ScheduledService { @Scheduled(cron = "0/1 * * * * ? ") public void sayHello(){ System.out.println("定時任務1:"+new Date()); } }
控制檯:
3、加入SayNo方法
@Scheduled(cron = "0/1 * * * * ? ")
public void sayNo(){
System.out.println("定時任務2"+new Date()+".......No");
}
此時啟動,會看到控制檯如下圖:此時是同步的,序列,先執行sayHello,再執行SayNo.
4、加上@Async
@SpringBootApplication
@EnableScheduling
@Async
public class ScheduledDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledDemoApplication.class, args);
}
}
再次檢視控制檯:如圖
此時不再是按順序去執行了,而是非同步。在啟動類加上@Async,表示執行的是非同步的