本篇仅限于 Spring 定时任务 & 异步调用的基本使用,不涉及深入原理探究,先学会怎么用,再探究原理.
环境:SpringBoot 2.0
定时任务指的是应用程序在指定的时间执行预先定义好的程序片段
在 Spring 中使用定时任务非常简便,分为三步:编写定时任务类并注入到 IOC 容器,一般使用 @Component 注入
编写定时任务方法并使用 @Scheduled 标记,这里需要了解一个叫 Cron 表达式的知识点
在 SpringBoot 启动类上使用 @EnableScheduling 开启定时任务功能
/*** 1、注入到 IOC 容器,定时任务不属于 service 或 controller,一般使用 @Component 标注*/
@Slf4j
@Component
public class HelloScheduled {
/*** 2、编写定时任务方法并使用 @Scheduled 标记* 注意:@Scheduled cron 属性中书写的是 cron 表达式,如下的 cron 表达式表示:每隔5秒执行一次*/
@Scheduled(cron = "*/5 * * * * ?")
public void scheduled() {
log.info("使用 Spring @Scheduled 制定定时任务");
}
}
/*** 3、在 `SpringBoot` 启动类上使用 `@EnableScheduling` 开启定时任务*/
@EnableScheduling
@SpringBootApplication
public class SpringAllApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAllApplication.class, args);
}
}
自定义配置文件
上述代码我们是在SpringBoot启动类上使用@EnableScheduling开启定时任务,而在实际开发我们会使用JavaConfig配置并约束package,使得指定的组件只有在指定package才有效.
/*** 定时任务只扫描 HelloScheduled 类所在的包*/
@EnableScheduling
@Configuration
@ComponentScan(basePackageClasses = com.xbhel.springall