Schedule:计划,任务。就是我们常说的定时任务。这在我们做一些系统的时候,是经常需要用到的。比如:定时更新一些数据,定时更新索引,都需要这样的一个功能。

第一:创建一个名为springboot-schedule的maven项目:

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>springboot-schedule</groupId>
<artifactId>springboot-schedule</artifactId>
<version>1.0.1</version>
<packaging>war</packaging> <name>springboot-schedule</name>
<description>这是springboot定时任务</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath></relativePath>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <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>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--打包跳过测试插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

  第二:创建主启动类:SpringBootApplication

  

 package shenlan;

 import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableScheduling; /**
* Created by wangwei on 2016/9/2.
*/
@org.springframework.boot.autoconfigure.SpringBootApplication
@EnableScheduling
public class SpringBootApplication {
public static void main(String[] args){
SpringApplication.run(SpringBootApplication.class,args);
}
}
 @EnableScheduling这是任务所必须的一个注解,有了这个注解,我们的项目才能开启定时任务的能力。
最后一步,开启我们的测试吧:
 package shenlan.web;

 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; /**
* Created by wangwei on 2016/9/2.
*/
@Component
public class Task {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Scheduled(cron="*/3 * * * * *")
public void reportCurrentTime(){
//每三秒打印一行log
System.out.println("-------------------------------------");
logger.info("======================");
}
}

这里用到了cron技术,不懂的学森可以恶补一下cron的知识哦,很有用,很实用。

启动项目后,能看见以下console输出,就代表你成功啦,恭喜你!

SpringBoot专题2----springboot与schedule的激情相拥-LMLPHP

本博客的完整代码:https://github.com/shenlanzhizunjustwangwei/springBoot/tree/master/springboot-schedule

schedule,你值得拥有!

如果你觉得本博客对你有帮助,别忘了请我喝茶哦!

SpringBoot专题2----springboot与schedule的激情相拥-LMLPHP                    SpringBoot专题2----springboot与schedule的激情相拥-LMLPHP

05-11 22:56