1.在启动类上添加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class RunApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(RunApplication.class, args);
}
}
2.在要执行的类上添加注解@Scheduled(cron = "0/5 * * * * ? ")
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Timing {
@Scheduled(cron = "0/5 * * * * ? ") // 每5秒执行一次
public void task() {
System.out.println(GetDateUtil.getDate3() + "定时任务");
}
}
结果