Spring boot @EnableScheduling 和 @Scheduled 注解使用例子

前言

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
posted @ 2018-10-14 12:34  风一样的码农  阅读(8508)  评论(4编辑  收藏  举报