the command-line runners can be used as a place to start the scheduled executor thread pool in order to run the worker threads in intervals.虽然这是可行的,但Spring为我们提供了一个更简洁的配置来完成同样
的目标:@EnableScheduling
先给Application类加上@EnableScheduling注解
@SpringBootApplication
@EnableScheduling
public class BookPubApplication {
@Bean
public StartupRunner schedulerRunner() {
return new StartupRunner();
}
public static void main(String[] args) {
SpringApplication.run(BookPubApplication.class, args);
}
}
@Scheduled只能用在无参方法上
public class StartupRunner implements CommandLineRunner {
Log logger = LogFactory.getLog(getClass());
@Autowired
private BookRepository bookRepository;
@Override
public void run(String... args) throws Exception {
logger.info("Number of books: " + bookRepository.count());
}
@Scheduled(initialDelay = 1000, fixedRate = 3000)
public void run() {
logger.info("Number of books: " + bookRepository.count());
}
}
@EnableScheduling不是一个Spring Boot注解,而是一个Spring Context模块注解。它和
@SpringBootApplication以及@EnableAutoConfiguration一样都是元注解。它在内部利用@Import
导入了SchedulingConfiguration,而它又会创建ScheduledAnnotationBeanPostProcessor,接着
扫描那些存在@Scheduled注解的Spring Beans,对于每一个无参的被注解的方法,相应的executor
thread pool会被创建出来。