@SpringBootApplication @EnableScheduling @EnableConfigurationProperties({TimerTask.class}) public class ScheduleTaskApp { public static void main(String[] args) { SpringApplication.run(ScheduleTaskApp.class, args); } }
@Component @ConfigurationProperties(prefix = "schedule") public class TimerTask implements InitializingBean { private String dateFormatter; private SimpleDateFormat sdf; @Scheduled(fixedRate = 2000) public void run() { System.out.println(String.format("%s: run is called !", sdf.format(new Date()))); } @Override public void afterPropertiesSet() throws Exception { sdf = new SimpleDateFormat(dateFormatter); } public String getDateFormatter() { return dateFormatter; } public void setDateFormatter(String dateFormatter) { this.dateFormatter = dateFormatter; } }
这段代码在启动后发现没2秒实际执行了两次run方法,
去掉Component注解后问题解决