Java - SpringBoot - 2.x - 任务管理 - 定时 - 使用Spring 的 Scheduled实现定时任务

参考

特点

  • 默认单线程执行任务,多任务阻塞运行

使用

1、启动类使用@EnableScheduling注解开启定时任务

@SpringBootApplication @EnableScheduling public class ScheduledTest { public static void main(String[] args) { SpringApplication.run(ScheduledTest.class); } }

2.2、添加定时任务(2种方式)

方式一:使用@Scheduled注解

@Slf4j @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(cron = "0/2 * * * * ? ") public void task1() { log.info("定时任务1,每2秒执行一次,time: {}", dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName()); } }

方式二:实现SchedulingConfigurer接口

@Configuration @Component @Slf4j public class TestTask implements SchedulingConfigurer { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addFixedDelayTask(this::index2, 1000); } public void index2() { log.info("定时任务2,每1秒执行一次,time:" + dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName()); } }

思考与进阶

多处部署的问题:每处都会执行一次定时任务。
考虑使用支持分布式的定时任务实现。


__EOF__

本文作者zxaben
本文链接https://www.cnblogs.com/zxaben/p/16120869.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   阿明,小明  阅读(110)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示