1. 启动类添加 @EnableScheduling 注解
- @SpringBootApplication
- // 开启定时任务
- @EnableScheduling
- public class StartDemoApplication { public static void main(String[] args) {
- SpringApplication.run(StartDemoApplication.class, args);
- }
- }
2. 建立定时任务, 使用 @Component 注解
- @Component
- public class TestTask {
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
- // 定义每过 3 秒执行任务
- @Scheduled(fixedRate = 3000)
- public void reportCurrentTime() {
- System.out.println(dateFormat.format(new Date()));
- }
- }
定时任务表达式
@Scheduled(cron = "")
cron 支持 6 位
表达式参考网址 cron.qqe2.com
如: @Scheduled(cron = "0/5 * * * * ?")
来源: http://www.bubuko.com/infodetail-2756568.html