赞
踩
记录一下动态生成定时任务和更新定时任务配置的开发经验
目录
1.实现定时任务配置接口,在此自定义定时任务创建策略,动态管理定时任务
工作中有需要应用到定时任务的场景,如一天一次,一周一次,一月一次,一年一次,做日报,周报,月报,年报的统计,以及信息提醒等,spring boot 提供了一个两种方式实现定时任务。第一种是静态的创建——基于注解,第二种是自定义配置——基于接口。我的业务场景是通过配置监控时间段和监控频率来对服务监控,因此需要动态创建定时任务。
1、保证ConcurrentTaskScheduler不使用默认单线程的ScheduledExecutor,而是corePoolSize=5的线程池
2、自定义线程池工厂类
- import org.springframework.beans.factory.config.BeanDefinition;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.Role;
- import org.springframework.scheduling.annotation.EnableScheduling;
- import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
-
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ThreadFactory;
- import java.util.concurrent.atomic.AtomicInteger;
-
- @Configuration
- @EnableScheduling
- @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
- public class TaskConfiguration {
-
- @Bean(name = ScheduledAnnotationBeanPostProcessor.DEFAULT_TASK_SCHEDUL

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。