springboot schedule 解决定时任务不执行的问题

作者:为湖 时间:2021-05-30 05:00:38 

@schedule 注解 是springboot 常用的定时任务注解,使用起来简单方便,但是如果定时任务非常多,或者有的任务很耗时,会影响到其他定时任务的执行,因为schedule 默认是单线程的,一个任务在执行时,其他任务是不能执行的.解决办法是重新配置schedule,改为多线程执行.只需要增加下面的配置类就可以了.


import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
 @Override
 public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
   Method[] methods = BatchProperties.Job.class.getMethods();
   int defaultPoolSize = 3;
   int corePoolSize = 0;
   if (methods != null && methods.length > 0) {
     for (Method method : methods) {
       Scheduled annotation = method.getAnnotation(Scheduled.class);
       if (annotation != null) {
         corePoolSize++;
       }
     }
     if (defaultPoolSize > corePoolSize)
       corePoolSize = defaultPoolSize;
   }
   taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
 }
}

源码  https://github.com/Yanyf765/demo_schedule

总结

以上所述是小编给大家介绍的springboot schedule 解决定时任务不执行的问题,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:https://blog.csdn.net/u012954380/article/details/92107902

标签:springboot,定时任务
0
投稿

猜你喜欢

  • Android编写简单的网络爬虫

    2023-09-24 03:44:52
  • 浅谈Maven的安装及修改为阿里云下载依赖

    2023-08-05 08:30:37
  • C语言实现餐饮管理系统

    2023-03-26 06:40:37
  • 深度剖析java动态静态代理原理源码

    2021-10-25 08:10:31
  • springcloud使用Hystrix进行微服务降级管理

    2023-02-02 06:51:30
  • IDEA(jetbrain通用)使用教程图解

    2023-04-15 04:05:49
  • 【Java IO流】字节流和字符流的实例讲解

    2023-08-08 20:45:58
  • Java Web实现自动登陆功能

    2023-09-06 04:17:53
  • java编程求二叉树最大路径问题代码分析

    2023-03-16 20:44:16
  • Android编程之动态壁纸实例分析

    2023-02-23 07:05:15
  • IntelliJ IDEA各种图标的含义

    2022-08-12 21:50:25
  • java实现多人聊天室可视化

    2021-08-27 01:16:49
  • Android中GridView插件的使用方法

    2021-07-26 16:46:28
  • Java算法设计与分析分治算法

    2022-04-02 08:07:15
  • Java 实现模拟用户登录的示例代码

    2022-10-16 04:23:06
  • Java从服务端下载Excel模板文件的两种方法

    2021-08-29 05:44:40
  • Android Jetpack组件中LifeCycle作用详细介绍

    2022-05-14 04:56:15
  • Spring Boot利用@Async如何实现异步调用:自定义线程池

    2021-11-09 17:32:11
  • WPF实现绘制扇形统计图的示例代码

    2021-11-29 23:42:00
  • SpringBoot2.0整合jackson配置日期格式化和反序列化的实现

    2022-06-29 14:13:52
  • asp之家 软件编程 m.aspxhome.com