原文链接:http://www.dubby.cn/detail.html?id=9046
本文简单介绍在Spring项目中怎么使用定时任务.
1. 你需要准备的
- JDK 1.8 +
- Maven 3.0+
2. 动手写代码
2.1 项目依赖
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>cn.dubby</groupId>
<artifactId>scheduling-tasks</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
可以看到,只需要最基本的依赖就可以了.
2.2 创建一个任务
src/main/java/hello/ScheduledTasks.java
package hello;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 1000)
public void fixedRate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println("fixedRate\t:\t" + dateFormat.format(new Date()));
}
@Scheduled(cron = "10 * * * * *")
public void cron() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println("cron\t\t:\t" + dateFormat.format(new Date()));
}
}
@Scheduled
这个注解修饰的方法会被定时调用,这里只演示了fixedRate
和cron
两种用法,这也是最常用的两种,其他定义方式可以自己看他的属性.
2.3 开启定时任务
src/main/java/hello/Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
这里就多了个@EnableScheduling
,它的名字也很明显的说明了他的作用,没错,就是开启定时任务.
本文介绍的只是单机的定时任务,如果一个应用有多个实例,那么仅仅本文的内容是不够的.你可能需要保证集群内只有一个实例会运行定时任务.有很多成熟的工具包或框架,一般都需要借助存储来保证.有兴趣的可以自行搜索学习.