1.在启动类里面使用@EnableScheduling 注解开启功能,其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling //开启定时任务
public class CedApplication {
public static void main(String[] args) {
SpringApplication.run(CedApplication.class, args);
}
}
2.创建定时任务Java类
注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任务。
@Component
public class TaskTest {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(cron = "0/3 * * * * ?")
public static void taskTest(){
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}
}
执行结果:
cron表达式规则:https://www.cnblogs.com/dubhlinn/p/10740838.html
在线Cron表达式生成器:https://cron.qqe2.com/