1、引包
pom 包里面只需要引入 Spring Boot Starter 包即可
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
2、创建定时任务
@Component
注解或@Service
注解标注在定时任务方法所在类上
@Scheduled
注解标注在执行方法上
package com.example.springboot_demo.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduleTask {
@Scheduled(cron = "0/4 * * * * *")
public void sayHello(){
System.out.println("-----------------------------------hello 20210607-------------------------------------------");
}
}
3、开启定时任务
在启动类上面加上@EnableScheduling
即可开启定时
@EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = "com.example.springboot_demo.mapper")
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
cron表达式:
second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
0 0/5 14,18 * * ? 每天14点整,和18点整,每隔5分钟执行一次
0 15 10 ? * 1-6 每个月的周一至周六10:15分执行一次
0 0 2 ? * 6L 每个月的最后一个周六凌晨2点执行一次
0 0 2 LW * ? 每个月的最后一个工作日凌晨2点执行一次
0 0 2-4 ? * 1#1 每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;