您的位置:首页 > 编程语言 > Java开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: