1.运行环境
开发工具:intellij idea
JDK版本:1.8
项目管理工具:Maven 4.0.0
2.Maven Plugin管理
pom.xml配置代码:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>spring-boot-scheduler</groupId> 8 <artifactId>spring-boot-scheduler</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <!-- Spring Boot 启动父依赖 --> 12 <parent> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-starter-parent</artifactId> 15 <version>1.5.6.RELEASE</version> 16 </parent> 17 18 <dependencies> 19 <!-- Spring Boot web依赖 --> 20 <dependency> 21 <groupId>org.springframework.boot</groupId> 22 <artifactId>spring-boot-starter-web</artifactId> 23 </dependency> 24 <!-- Spring Boot test依赖 --> 25 <dependency> 26 <groupId>org.springframework.boot</groupId> 27 <artifactId>spring-boot-starter-test</artifactId> 28 <scope>test</scope> 29 </dependency> 30 </dependencies> 31 32 33 </project>
3.Application启动类编写
通过@EnableScheduling激活上下文中的所有定时任务;如果我们没有这个标注,所有@Scheduled
标注都不会执行。
1 package com.goku.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.boot.web.servlet.ServletComponentScan; 6 import org.springframework.scheduling.annotation.EnableScheduling; 7 8 /** 9 * Created by nbfujx on 2017/11/20. 10 */ 11 // Spring Boot 应用的标识 12 @SpringBootApplication 13 @ServletComponentScan 14 @EnableScheduling 15 public class DemoApplication { 16 17 public static void main(String[] args) { 18 // 程序启动入口 19 // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件 20 SpringApplication.run(DemoApplication.class,args); 21 } 22 }
4.Scheduled Task创建
通过@Scheduled标注表示这个方法是需要定时执行的任务。
1 package com.goku.demo.scheduler; 2 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 import org.springframework.scheduling.annotation.Scheduled; 6 import org.springframework.stereotype.Component; 7 8 /** 9 * Created by nbfujx on 2017/12/6. 10 */ 11 @Component 12 public class ExampleScheduler { 13 14 private final Logger logger = LoggerFactory.getLogger(getClass()); 15 16 @Scheduled(cron = "*/5 * * * * * ") 17 public void loginfo() { 18 this.logger.info("this is one"); 19 } 20 21 @Scheduled(fixedRate = 5000) 22 public void loginfo2() { 23 this.logger.info("this is two"); 24 } 25 26 @Scheduled(fixedDelay = 5000) 27 public void loginfo3() { 28 this.logger.info("this is three"); 29 } 30 }
- fixedRate = 5000表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
- fixedDelay = 5000表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法
- cron = "*/5 * * * * * ?"提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次,更加详细的信息可以参考cron表达式。
5.查看运行情况
6.GITHUB地址
https://github.com/nbfujx/springBoot-learn-demo/tree/master/spring-boot-scheduler