当前位置:   article > 正文

【Scheduled定时任务】spring boot动态生成定时任务_scheduled 生成

scheduled 生成

记录一下动态生成定时任务和更新定时任务配置的开发经验

目录

前言

一、自定义定时任务配置类

二、实现SchedulingConfigurer接口

1.实现定时任务配置接口,在此自定义定时任务创建策略,动态管理定时任务

2.测试类

3.运行截图

总结


前言

工作中有需要应用到定时任务的场景,如一天一次,一周一次,一月一次,一年一次,做日报,周报,月报,年报的统计,以及信息提醒等,spring boot 提供了一个两种方式实现定时任务。第一种是静态的创建——基于注解,第二种是自定义配置——基于接口。我的业务场景是通过配置监控时间段和监控频率来对服务监控,因此需要动态创建定时任务。


一、自定义定时任务配置类

        1、保证ConcurrentTaskScheduler不使用默认单线程的ScheduledExecutor,而是corePoolSize=5的线程池

  2、自定义线程池工厂类

  1. import org.springframework.beans.factory.config.BeanDefinition;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.Role;
  5. import org.springframework.scheduling.annotation.EnableScheduling;
  6. import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.ScheduledExecutorService;
  9. import java.util.concurrent.ThreadFactory;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11. @Configuration
  12. @EnableScheduling
  13. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  14. public class TaskConfiguration {
  15. @Bean(name = ScheduledAnnotationBeanPostProcessor.DEFAULT_TASK_SCHEDUL
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52286
推荐阅读
相关标签
  

闽ICP备14008679号