SpringBoot - 定时任务
定时任务是企业级开发中最常见的功能之一,如定时统计订单数、定时进行数据库备份、定时发送邮件等。简单的定时任务可以直接通过 Spring 的 @Scheduled 注解实现,复杂的定时任务则可以通过集成 Quartz 来实现。本文先介绍前者。
一、使用 @Scheduled 注解实现定时任务
1,开启定时任务
首先在项目启动类上添加 @EnableScheduling 注解开启定时任务:
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context
= SpringApplication.run(DemoApplication.class, args);
}
}
2,配置定时任务
定时任务主要通过 @Scheduled 注解进行配置,代码如下:
@Component
public class MySchedule {
// 当前任务执行结束1秒后开启另一个任务
@Scheduled(fixedDelay = 1000)
public void fixedDelay() {
System.out.println("fixedDelay:"+new Date());
}
// 当前任务开始执行2秒后