【转载】Springboot2.x 使用 @Scheduled 实现定时任务

参考

  1. https://cloud.tencent.com/developer/article/1445905 (定时任务实现方法)
  2. https://www.jianshu.com/p/ff876c2ab24a (@Scheduled使用)
  3. https://blog.csdn.net/luolearn/article/details/119565954 (cron学习)

注意

  1. 实现定时任务的方法不仅这一种
  2. 定时任务也可以同时执行多个线程(描述不准确,大概理解吧)
  3. 定时任务默认单线程,建议开启异步任务或多线程任务,防止堵塞

步骤

  1. 在入口文件添加注解 @EnableScheduling 开启定时任务。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class XiaQiuChuApplication {
    public static void main(String[] args) {
        SpringApplication.run(XiaQiuChuApplication.class, args);
    }

}
  1. 在要定时执行的方法上标注注解 @Scheduled(cron = "0/5 * * * * ?") 实现每5s 执行一次。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class XiaQiuChuTestScheduled {
    @Scheduled(cron = "0/5 * * * * ?")
    public void scheduled(){
        System.out.println("定时任务测试");
        log.info("=====>>>>>使用cron  {}",System.currentTimeMillis());
    }
}
posted @ 2022-05-21 10:01  夏秋初  阅读(55)  评论(0)    收藏  举报