如何设置Spring Boot中的定时任务执行策略?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2822个文字,预计阅读时间需要12分钟。
概述+在Java环境下创建定时任务有多种方式:+使用while循环配合Thread.sleep(),简单但不够强大+使用Timer和TimerTask,功能更丰富+使用ScheduledExecutorService定时任务框架,如Quartz+在SpringBoot下使用
概述
在Java环境下创建定时任务有多种方式:
- 使用while循环配合 Thread.sleep(),虽然稍嫌粗陋但也勉强可用
- 使用 Timer和 TimerTask
- 使用 ScheduledExecutorService
- 定时任务框架,如Quartz
在SpringBoot下执行定时任务无非也就这几种方式(主要还是后两种)。只不过SpringBoot做了许多底层的工作,我们只需要做些简单的配置就行了。
通过注解实现定时任务
在SpringBoot中仅通过注解就可以实现常用的定时任务。步骤就两步:
在启动类中添加 @EnableScheduling注解
@EnableScheduling @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
在目标方法中添加 @Scheduled注解,同时在 @Scheduled注解中添加触发定时任务的元数据。
本文共计2822个文字,预计阅读时间需要12分钟。
概述+在Java环境下创建定时任务有多种方式:+使用while循环配合Thread.sleep(),简单但不够强大+使用Timer和TimerTask,功能更丰富+使用ScheduledExecutorService定时任务框架,如Quartz+在SpringBoot下使用
概述
在Java环境下创建定时任务有多种方式:
- 使用while循环配合 Thread.sleep(),虽然稍嫌粗陋但也勉强可用
- 使用 Timer和 TimerTask
- 使用 ScheduledExecutorService
- 定时任务框架,如Quartz
在SpringBoot下执行定时任务无非也就这几种方式(主要还是后两种)。只不过SpringBoot做了许多底层的工作,我们只需要做些简单的配置就行了。
通过注解实现定时任务
在SpringBoot中仅通过注解就可以实现常用的定时任务。步骤就两步:
在启动类中添加 @EnableScheduling注解
@EnableScheduling @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
在目标方法中添加 @Scheduled注解,同时在 @Scheduled注解中添加触发定时任务的元数据。

