概述
- 需要周期性的实现某些功能逻辑,就要用到定时任务,以下简单介绍一下定时器在SpringBoot中的实现方法。
添加启用注解
- 在启动类或配置类中加添启用定时器的注解
@EnableScheduling
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
添加执行方法
@Component
@Slf4j
public class DemoTask {
@Scheduled(cron = "0/10 * * * * ?")
public void execute() {
log.info("正在执行定时任务,当前时间:{}", new Date());
}
}
备注
- 1.默认情况下,只有一个单一线程在执行定时任务,如果有多个定时任务要执行,最好使用异步的方式。
- 2.开启异步:在启动类或配置类中添加
@EnableAsync
,然后在执行方法上添加@Async