几乎大部分的应用都会有定时执行任务的需求。使用Spring Boot的Scheduling Tasks能够提高您的开发效率。这篇文章将介绍怎么通过Spring Boot去做调度任务。
构建工程
创建一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务。
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}
创建定时任务
创建一个定时任务,每过2s在控制台打印当前时间。
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 2000)
public void reportCurrentTime() {
log.info("The time is : " + dateFormat.format(new Date()));
}
}
通过在方法上加@Scheduled注解,表明该方法是一个调度任务。
- @Scheduled(fixedRate = 2000) :上一次开始执行时间点之后2秒再执行
- @Scheduled(fixedDelay = 2000) :上一次执行完毕时间点之后2秒再执行
- @Scheduled(initialDelay=1000, fixedRate=2000) :第一次延迟1秒后执行,之后按fixedRate的规则每2秒执行一次
- @Scheduled(cron=" /2 ") :通过cron表达式定义规则
测试
启动springboot工程,控制台没过2s就打印出了当前的时间。
总结
在springboot创建定时任务比较简单,只需2步:
- 在程序的入口加上@EnableScheduling注解。
- 在定时方法上加@Scheduled注解。