在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置
@Component
public class ScheduledTasks {
// @Scheduled创建定时任务
@Scheduled(fixedRate = 1000)
public void test() {
// 执行任务调度方法
System.out.println("我正在每隔1秒打印...");
}
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
代码托管:springboot_scheduled