基于Spring Boot 实现定时任务
2018-03-27 15:50
344 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/klq123/article/details/79714169
基于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应用即可。
相关文章推荐
- 基于Spring Boot 实现定时任务
- 【转载】基于Spring Boot 实现定时任务
- spring boot-使用redis的Keyspace Notifications实现定时任务队列
- SpringBoot之旅 -- 定时任务两种(Spring Schedule 与 Quartz 整合 )实现
- SpringBoot三种方式实现定时任务
- springboot整合Quartz实现动态配置定时任务
- springboot中使用@EnableScheuling注解来实现数据库配置定时任务
- Quartz实现JAVA定时任务的动态配置(Spring boot)
- 在Spring Boot中使用@Scheduled实现定时任务
- SpringBoot@Scheduled实现定时任务
- springboot整合Quartz实现动态配置定时任务
- springboot整合Quartz实现动态配置定时任务的方法
- 在Spring Boot中使用@Scheduled实现定时任务
- SpringBoot中并发定时任务的实现、动态定时任务的实现(看这一篇就够了)推荐
- Springboot中定时任务的实现
- SpringBoot (五) 实现定时任务
- spring boot + Schedule简单定时任务实现
- 在Spring Boot中使用@Scheduled实现定时任务
- SpringBoot整合Quartz实现定时任务(单任务、多任务)
- springboot集成schedule实现定时任务