SpringBoot定时任务——Scheduled定时任务器
Scheduled定时任务器
Scheduled定时任务器:是Spring3.0以后自带的定时任务器
导入相关依赖
- pom.xml,Springboot的Web启动器中没有包含Scheduled的相关的jar包,所以 要添加相关的依赖
<!-- 添加Scheduled依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
写定时任务方法
@Scheduled注解设置定时任务方法,用Cron表达式触发定时任务方法
@Component
public class ScheduledDemo {
/**
* Scheduled定时任务
*/
@Scheduled(cron = "0/1 * * * * ?")
public void scheduledMethod(){
System.out.println("我是一个定时任务"+new Date());
}
}
启动类中开启定时任务的启动
SpringBoot默认定时任务是关闭的,使用@EnableScheduling
注解进行开启定时任务的操作。
@SpringBootApplication
@EnableScheduling
public class TaskCenterApplication {
public static void main(String[] args) {
SpringApplication.run(TaskCenterApplication.class);
}
}
使用比较简单。
Cron表达式
基于字符串的一种对时间的规定格式,分为6域和7域。日要搭配月否则会出错
语法
位置 | 时间域名 | 允许值 |
---|---|---|
1 | 秒 | 0-59 |
2 | 分钟 | 0-59 |
3 | 小时 | 0-23 |
4 | 日 | 1-31 |
5 | 月 | 1-12 |
6 | 星期 | 1-7 |
7 | 年(可选) | 1970-2099 |
3 * * * * * ? #每分钟的第3秒触发
3 50 18 31 * ? # 每个月的31号18:50:03秒执行任务
3 50 18 * 3 4 #3月份的每个星期3 18:50:03秒执行任务
10,15 * 18 * 2 ? #2月份的每一天的18点的每分钟的第10和第15秒执行任务
0/1 * * * * * #间隔1秒执行任务
-
*:表示任意一个。
-
?:表示占位符号没有实际意义
-
-:表示范围内的。
-
,:表示列表值
- #:间隔1秒执行任务