它的作用就是,你设置一个时间段或者设置每隔多久执行一次东西 Scheduled是系统自带的所以只要有web依赖就可以了 web依赖全名:spring-boot-starter-web
缺点: Spring定时任务存在的问题:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
server:
port: 9090
@Scheduled(cron = “写执行时间表达上”)
@Component
public class MyTask {
//cron 一共可以有7个参数,以空格分开,年不是必须参数
//[秒] [分] [小时] [日] [月] [周] [年]
//每天凌晨零点执行
@Scheduled(cron ="0 0 0 * * * ?")
public void run() {
System.out.println("到00:00啦,代码开始执行了");
}
}
package com.zb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling //启动定时任务
public class AllApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(AllApplication.class, args);
}
}
cron它是一个表达式,最多接收7个参数 从左到右分别表示:秒 分 时 天 月 周 年; 参数以空格隔开,其中年不是必须参数,可以省略
cron参数:
含义 | 是否必须 | 参数范围 | 可填通配符 |
---|---|---|---|
秒 | 是 | 0-59 | , - * / |
分 | 是 | 0-59 | , - * / |
时 | 是 | 0-23 | , - * / |
日 | 是 | 1-31 | , - * ? / L W |
月 | 是 | 1-12 | , - * / |
周 | 是 | 1-7 | , - * ? / L # |
年 | 是 | 1970-2099 | , - * / |
常用通配符: *:表示所有值 比如用在日 表示每一天。
?:表示不指定值 比如周配置 表示不指定星期几执行。
/:表示递增触发 比如 用在分 5/20 从第五分钟开始 每增加20分钟执行一次。
-:表示区间 比如用在 1-6 表示一月到六月执行。
@Scheduled(cron ="0 0 0 * * * ?")
@Scheduled(cron ="0 */5 0 * * * ?")
更多详细解释请前往:https://blog.csdn.net/sunp_csdn/article/details/122824185