Spring @EnableScheduling 注解解析

概述

Spring 的@EnableScheduling 为我们提供了快速的基于多种规则的任务调度功能。在《Spring 4.x Task 和 Schedule 概述》一文中对Spring 实现的异步任务和定时计划作了概要性的介绍,本文将对其实现原理进行解析。

核心原理

@EnableScheduling

要使用Spring 的注解@Scheduled 来快速开启任务调度功能,只需要添加如下配置:

@Configuration
@EnableScheduling
public class ScheduleConfig {
}

@EnableScheduling 注解对应的内容如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
@Documented
public @interface EnableScheduling {

}

由上可以看到实际上是SchedulingConfiguration.class 类实现了Spring 的任务调度框架级功能。该配置类仅仅是定义了ScheduledAnnotationBeanPostProcessor 的实例。Spring 的调度功能由该实例进行配置。

查看更多内容>>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@EnableScheduling 是 Spring 框架中提供的一个注解,用于开启基于注解的定时任务。其主要作用是扫描带有 @Scheduled 注解的方法,并在指定的时间间隔内执行这些方法。 该注解的源码如下: ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(SchedulingConfiguration.class) public @interface EnableScheduling { } ``` 可以看到,该注解使用了 @Import 注解,导入了 SchedulingConfiguration 类。这个类是 Spring 中的一个配置类,它实现了 SchedulingConfigurer 接口,用于配置任务调度器。 SchedulingConfiguration 类的源码如下: ```java @Configuration @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public class SchedulingConfiguration implements SchedulingConfigurer { private volatile ScheduledTaskRegistrar taskRegistrar; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { Assert.notNull(taskRegistrar, "ScheduledTaskRegistrar must not be null"); if (this.taskRegistrar != null && taskRegistrar != this.taskRegistrar) { throw new IllegalStateException("Only one ScheduledTaskRegistrar may exist"); } this.taskRegistrar = taskRegistrar; } @Bean(destroyMethod = "destroy") @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public TaskScheduler taskScheduler() { return createDefaultTaskScheduler(); } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public AnnotationAsyncExecutionAspect asyncExecutionAspect() { return AnnotationAsyncExecutionAspect.aspectOf(); } private TaskScheduler createDefaultTaskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadNamePrefix("spring-task-scheduler-"); return scheduler; } } ``` 可以看到,该类中定义了一个 taskScheduler() 方法,用于创建默认的任务调度器。同时,它还实现了 SchedulingConfigurer 接口,重写了 configureTasks() 方法,用于配置任务调度器。 总的来说,@EnableScheduling 注解的作用就是开启 Spring 的定时任务功能,通过扫描带有 @Scheduled 注解的方法,自动创建定时任务并执行。同时,它还提供了一些默认的配置,例如默认的任务调度器等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值