f 物联网-Spring Boot 实现定时任务 - Powered by qidao123.com技术社区

Spring Boot 实现定时任务

打印 上一主题 下一主题

主题 1896|帖子 1896|积分 5688

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. 启用定时任务支持

起首,需要在 Spring Boot 应用的主类大概任何配置类中添加 @EnableScheduling 注解,以启用定时任务支持。
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.scheduling.annotation.EnableScheduling;
  4. @SpringBootApplication
  5. @EnableScheduling
  6. public class MyApplication {
  7.     public static void main(String[] args) {
  8.         SpringApplication.run(MyApplication.class, args);
  9.     }
  10. }
复制代码

2. 创建定时任务方法

接下来,可以在任意的 Spring Bean(通常是一个 @Service 或 @Component)中创建一个利用 @Scheduled 注解的方法。该方法会根据指定的时间间隔或触发条件自动实行。
2.1 利用 @Scheduled 注解

@Scheduled 注解支持多种情势的时间配置:


  • fixedRate:按照固定的时间间隔(以毫秒为单位)实行,任务开始时盘算间隔。
  • fixedDelay:按照固定的延迟(以毫秒为单位)实行,任务完成后盘算间隔。
  • cron:利用 Cron 表达式指定实行时间。
示例代码:

  1. import org.springframework.scheduling.annotation.Scheduled;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class MyScheduledTasks {
  5.     // 每隔5秒执行一次
  6.     @Scheduled(fixedRate = 5000)
  7.     public void executeTaskWithFixedRate() {
  8.         System.out.println("Task executed at fixed rate: " + System.currentTimeMillis());
  9.     }
  10.     // 上一个任务完成后5秒执行
  11.     @Scheduled(fixedDelay = 5000)
  12.     public void executeTaskWithFixedDelay() {
  13.         System.out.println("Task executed with fixed delay: " + System.currentTimeMillis());
  14.     }
  15.     // 每天早上8点执行
  16.     @Scheduled(cron = "0 0 8 * * ?")
  17.     public void executeTaskWithCronExpression() {
  18.         System.out.println("Task executed using cron expression: " + System.currentTimeMillis());
  19.     }
  20. }
复制代码

3. 配置 @Scheduled 参数

Spring Boot 中的 @Scheduled 注解支持配置文件中的参数,如许可以机动地修改定时任务的实行间隔或时间,而无需修改代码。
示例:

在 application.properties 或 application.yml 中定义参数:
  1. myapp.scheduling.fixed-rate=5000
  2. myapp.scheduling.cron=0 0 8 * * ?
复制代码

然后在代码中利用 @Value 注解注入这些参数:
  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.scheduling.annotation.Scheduled;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class MyScheduledTasks {
  6.     @Value("${myapp.scheduling.fixed-rate}")
  7.     private long fixedRate;
  8.     @Value("${myapp.scheduling.cron}")
  9.     private String cronExpression;
  10.     @Scheduled(fixedRateString = "${myapp.scheduling.fixed-rate}")
  11.     public void executeTaskWithFixedRate() {
  12.         System.out.println("Task executed at fixed rate: " + System.currentTimeMillis());
  13.     }
  14.     @Scheduled(cron = "${myapp.scheduling.cron}")
  15.     public void executeTaskWithCronExpression() {
  16.         System.out.println("Task executed using cron expression: " + System.currentTimeMillis());
  17.     }
  18. }
复制代码

总结

      Spring Boot 是基于Spring框架的一个开发框架,它提供了一种简化的方式来开发独立的、独立的、可实行的Spring应用程序。在Spring Boot中实现定时任务可以帮助我们在特定的时间间隔内实行一些特定的任务。本文将以层级的方式总结Spring Boot实现定时任务的相关知识。

  • 理解定时任务 定时任务是在特定的时间间隔内实行某个任务的机制。Spring Boot提供了一个注解@EnableScheduling,可以开启定时任务的支持。利用该注解后,只需要在任意一个Spring Bean的方法上添加注解@Scheduled,即可定义一个定时任务。
  • 注解@Scheduled @Scheduled可以用于标记一个方法是一个定时任务。它可以担当多个参数来指定任务的实行时间。此中常用的参数有:


  • fixedRate: 指定任务的实行频率,单位是毫秒。例如,@Scheduled(fixedRate = 1000)表示任务每秒实行一次。
  • fixedDelay: 指定任务之间的延迟时间,单位是毫秒。例如,@Scheduled(fixedDelay = 1000)表示任务实行完毕后,延迟1秒再实行下一次任务。
  • cron: 利用Cron表达式来定义任务的实行时间。例如,@Scheduled(cron = "0 0 0 * * ?")表示天天破晓零点实行任务。

  • 定时任务的实行 定时任务默认是在Spring Boot应用程序的启动时自动实行的。可以通过设置参数spring.task.scheduling.enabled=false来禁用自动实行。如果需要在特定的时间启动定时任务,可以利用注解@PostConstruct来标记一个方法,在该方法中手动启动定时任务。例如:
  1. @Component
  2. public class MyTask {
  3.     @PostConstruct
  4.     public void init() {
  5.         // 手动启动定时任务
  6.     }
  7.     @Scheduled(fixedRate = 1000)
  8.     public void doTask() {
  9.         // 定时任务的执行逻辑
  10.     }
  11. }
复制代码


  • 定时任务的线程池 Spring Boot利用一个线程池来实行定时任务,默认线程池巨细为1。如果有大量的定时任务,并发实行任务的本领大概会有所不敷。可以通过设置参数spring.task.scheduling.pool.size来调解线程池的巨细。例如,设置spring.task.scheduling.pool.size=10表示线程池巨细为10。
  • 异步定时任务 定时任务默认是同步实行的,即任务的实行会阻塞其他任务的实行。如果有需要并发实行的任务,可以利用注解@Async将定时任务标记为异步实行。例如:
  1. @Component
  2. public class MyTask {
  3.     @Async
  4.     @Scheduled(fixedRate = 1000)
  5.     public void doTask() {
  6.         // 异步执行的定时任务
  7.     }
  8. }
复制代码

需要注意的是,利用@Async注解的方法必须在一个被@Configuration注解的类中,并且该类必须被@EnableAsync注解开启异步支持。

  • 定时任务的非常处理 定时任务的实行过程中大概会出现非常。Spring Boot提供了一个接口SchedulingConfigurer,可以用来配置定时任务的非常处理器。可以通过实现该接口并重写configureTasks方法来自定义非常处理逻辑。例如:
  1. @Configuration
  2. @EnableScheduling
  3. public class MyTaskConfig implements SchedulingConfigurer {
  4.     @Override
  5.     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  6.         taskRegistrar.setScheduler(taskExecutor());
  7.     }
  8.     @Bean(destroyMethod = "shutdown")
  9.     public Executor taskExecutor() {
  10.         return Executors.newScheduledThreadPool(10);
  11.     }
  12. }
复制代码

在重写的configureTasks方法中,可以通过taskRegistrar.setScheduler方法来设置定时任务的线程池。在上述示例中,利用了Executors.newScheduledThreadPool(10)方法来创建一个线程池,巨细为10。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

写过一篇

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表