基于Spring Boot 实现定时任务
添加maven依赖
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
创建Scheduled Task
@Component
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Integer count0 = 1;
private Integer count1 = 1;
private Integer count2 = 1;
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() throws InterruptedException {
System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));
}
@Scheduled(fixedDelay = 5000)
public void reportCurrentTimeAfterSleep() throws InterruptedException {
System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));
}
@Scheduled(cron = "0 0 1 * * *")
public void reportCurrentTimeCron() throws InterruptedException {
System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));
}
}
在@Scheduled标注中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:
- fixedRate = 5000表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
- fixedDelay = 5000表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法
- cron = “/5 * * * * *”提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次,更加详细的信息可以参考cron表达式。
配置Scheduling
接下来我们通过Spring boot来配置一个最简单的Spring web应用,我们只需要一个带有main方法的类即可:
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
我们先来看看class上的标注:
1. @SpringBootApplication 实际上是了以下三个标注的集合:
- @Configuration 告诉Spring这是一个配置类,里面的所有标注了@Bean的方法的返回值将被注册为一个Bean
- @EnableAutoConfiguration 告诉Spring基于class path的设置、其他bean以及其他设置来为应用添加各种Bean
- @ComponentScan 告诉Spring扫描Class path下所有类来生成相应的Bean
2. @EnableScheduling 告诉Spring创建一个task executor,如果我们没有这个标注,所有@Scheduled标注都不会执行
通过以上标注,我们完成了schedule的基本配置。最后,我们添加main方法来启动一个Spring boot应用即可。