声明:本案例学习http://blog.youkuaiyun.com/je_ge,在此感谢je_ge提供的学习用的资料
1、项目目录结构
2、pom.xml的文件内容
<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.jege.spring.boot</groupId>
<artifactId>spring-boot-scheduled-task</artifactId>
<version>1.0.0.RELEASE</version>
<packaging>jar</packaging>
<name>spring-boot-scheduled-task</name>
<url>http://blog.youkuaiyun.com/je_ge</url>
<developers>
<developer>
<id>je_ge</id>
<name>je_ge</name>
<email>1272434821@qq.com</email>
<url>http://blog.youkuaiyun.com/je_ge</url>
<timezone>8</timezone>
</developer>
</developers>
<!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- web -->
<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>
<!-- 只在test测试里面运行 -->
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-scheduled-task</finalName>
<plugins>
<!-- jdk编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3、application.properties的内容
jobs.fixedDelay=5000
jobs.cron=0/5 * * * * ?
4、ScheduledTask的内容
package com.jege.spring.boot.task;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:从配置文件加载任务信息
*/
@Component
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedDelayString = "${jobs.fixedDelay}")
public void getTask1() {
System.out.println("任务1,当前时间:" + dateFormat.format(new Date()));
}
@Scheduled(cron = "${jobs.cron}")
public void getTask2() {
System.out.println("任务2,当前时间:" + dateFormat.format(new Date()));
}
}
5、Application的内容
package com.jege.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:spring boot 启动类
*/
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}