【转载】Springboot2.x 使用 @Scheduled 实现定时任务
参考
- https://cloud.tencent.com/developer/article/1445905 (定时任务实现方法)
- https://www.jianshu.com/p/ff876c2ab24a (@Scheduled使用)
- https://blog.csdn.net/luolearn/article/details/119565954 (cron学习)
注意
- 实现定时任务的方法不仅这一种
- 定时任务也可以同时执行多个线程(描述不准确,大概理解吧)
- 定时任务默认单线程,建议开启异步任务或多线程任务,防止堵塞
步骤
- 在入口文件添加注解
@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);
}
}
- 在要定时执行的方法上标注注解
@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());
}
}
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/16294499.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/16294499.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。

浙公网安备 33010602011771号