原文:http://mrw.so/57DDRR
Scheduled 定时任务器:是Spring3.0以后自带的一个定时任务器。我们来看下在SpringBoot中我们怎么使用
创建一个SpringBoot项目,并添加如下依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.1.7.RELEASE</version> </dependency></dependencies>
创建定时任务的java类,具体如下:
@Componentpublic class SchedueldDemo {
@Scheduled(cron = "0/2 * * * * ?") public void doSome(){ System.out.println("定时任务执行了:"+new Date()); }}
在启动器头部开启@EnableScheduling注解
@SpringBootApplication@EnableScheduling public class SpringBootSchedueldDemoApplication {
public static void main(String[] args) { SpringApplication.run(SpringBootSchedueldDemoApplication.class, args); }
}
启动后控制台如下:
Cron 表达式是一个字符串,分为 6 或 7 个域,每一个域代表一个含义 Cron 有如下两种语法格式:
Seconds Minutes Hours Day Month Week Year Seconds Minutes Hours Day Month Week
corn 从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份
位置 时间域名 允许值 允许的特殊字符 1 秒 0-59 , - * / 2 分钟 0-59 , - * / 3 小时 0-23 , - * / 4 日 1-31 , - * / L W C 5 月 1-12 , - * / 6 星期 1-7 , - * ? / L C # 7 年(可选) 1970-2099 , - * / Cron 表达式的时间字段除允许设置数值外,还可使用一些特殊的字符,提供列表、范围、通配符等功能,细说如下:
Cron 表达式对特殊字符的大小写不敏感,对代表星期的缩写英文大小写也不敏感。
例子:
@Scheduled(cron = “0 0 1 1 1 ?”)//每年一月的一号的 1:00:00 执行一次@Scheduled(cron = “0 0 1 1 1,6 ?”) //一月和六月的一号的 1:00:00 执行一次@Scheduled(cron = “0 0 1 1 1,4,7,10 ?”) //每个季度的第一个月的一号的 1:00:00 执行一次@Scheduled(cron = “0 0 1 1 * ?”)//每月一号 1:00:00 执行一次@Scheduled(cron=“0 0 1 * * *”) //每天凌晨 1 点执行一次