- 主启动类上开启定时任务,使用 @EnableScheduling
- 在需要定时执行的方法上,使用 @Scheduled(cron = " ")
- cron 表达式:设置执行的规则
3.1. 可借助在线工具生成需要的 cron 表达式,例如https://cron.qqe2.com/
@Component
public class ScheduleTask {
// 0/5 * * * * ?表示每隔5秒执行一次这个方法
@Scheduled(cron = "0/5 * * * * ?")
public void task() {
System.out.println("定时任务执行了");
}
}