一些时候,我们需要定时执行某些任务,在 spring boot 中已经有一些注解使用 「Scheduled」
- 1、 确保添加了依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
- 2、 声明使用 scheduled , 「@EnableScheduling」
@SpringBootApplication
@MapperScan("com.xiaocai.endorse.dao")
@EnableScheduling
public class EndorseApplication {
public static void main(String[] args) {
SpringApplication.run(EndorseApplication.class, args);
}
}
- 3、使用 「@Scheduled」
@Component
public class SchedulerTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 3000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
结果: 每隔 3 秒打印输出一次。
很简单是一个过程即可实现定时任务。