前言
好久没更新博客了,最近上班做了点小东西,总结复盘一下
参考资料:
SpringBoot 设置动态定时任务,千万别再写死了~ (qq.com)
3千字带你搞懂XXL-JOB任务调度平台-阿里云开发者社区 (aliyun.com)
一、定时任务
1. 引入依赖
创建Springboot应用,引入相应依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
在spring-boot-starter-web中排除spring-boot-starter-logging是为了不使用springboot默认的日志实现logback,而是引入log4j2的日志实现
引入lombok是为了使用@Data、@RequiredArgsConstructor等注解
2. 代码实现
在启动类上添加注解@EnableScheduling
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DttNoticeApplication {
public static void main(String[] args) {
SpringApplication.run(DttNoticeApplication.class, args);
}
}
配置文件指定运行的端口:
server:
port: 8080
编写实现定时任务的类,用@Scheduled修饰执行定时任务的方法,并用@Component将该类注册为Bean
package com.example.demo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Task{
// cron表达式常用于定时任务,此处表示每10秒执行一次
@Scheduled(cron="0/10 * * * * ?")
public void scheduledTask(){
// ...
}
}
二、动态定时任务
定时任务执行时间的配置文件,位于resources/task-config.ini:
printTime.cron=0/10 * * * * ?
编写实现定时任务的类,利用@PropertySource指定获取的配置文件并用@Value注入到相应成员中,并用@Component将该类注册为Bean
实现SchedulingConfigurer接口,重载configur