Spring boot @EnableScheduling 和 @Scheduled 注解使用例子
2018-10-14 12:34
841 查看
前言
Spring Boot提供了
@EnableScheduling和
@Scheduled注解,用于支持定时任务的执行,那么接下来就让我们学习下如何使用吧;
假设我们需要每隔10秒执行一个任务,那么我们可以按一下步骤来完成开发;
添加@EnableScheduling注解
在Spring Boot的启动类上添加
@EnableScheduling注解,
@EnableScheduling属于Spring Context 模块的注解,其内部通过
@Import(SchedulingConfiguration.class)注解引入了
SchedulingConfiguration;
添加注解代码示例如下:
@SpringBootApplication @EnableScheduling public class SpringBootWebApplication { }
添加@Scheduled注解
接下来我们就可以在需要执行定时任务的方法上添加
@Scheduled注解了,前提条件是该方法不能有参数;
对于每一个没有参数的方法,添加
@Scheduled注解后,都会被默认的线程池按计划执行;
代码示例:
@Scheduled(initialDelay = 1000, fixedRate = 10000) public void run() { logger.info("Current time is :: " + Calendar.getInstance().getTime()); }
控制台输出:
2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017 2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017 2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017 2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017 2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017
相关文章推荐
- spring boot 计划任务,定时任务的注解的使用@Scheduled@EnableScheduling
- spring boot @ConfigurationProperties @EnableConfigurationProperties 配置注解使用
- spring boot: 计划任务@ EnableScheduling和@Scheduled
- spring boot: @EnableScheduling开启计划任务支持,@Scheduled计划任务声明
- springBoot @Enable* 注解的使用
- Spring Boot 基于注解的 Redis 缓存使用
- Spring之——quartz使用@Scheduled注解执行定时任务
- Spring Boot2.x-05Spring Boot基础-使用注解完成依赖注入
- spring-boot使用注解获取配置文件中的值
- springboot @import @importResource 注解使用方式
- Spring-boot中使用@ConditionalOnExpression注解,在特定情况下初始化bean
- 在Spring Boot中使用@Scheduled实现定时任务
- springboot+springmvc+mybatis 使用注解对数据库的增、改和查操作
- 【HAVENT原创】使用 Spring Boot 的 AOP 自定义注解
- 在Spring Boot中使用@Scheduled实现定时任务
- 在Spring Boot中使用@Scheduled实现定时任务
- Springboot中注解使用
- SpringBoot 开启关闭自动任务配置(EnableScheduling )
- springboot 中使用websocket简单例子
- kaptcha的和springboot一起使用的简单例子