spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)

一、背景

spring boot的定时任务非常简单,只需要在启动类中加上@EnableScheduling注解,然后在对应的方法上配置@Scheduled就可以了,系统会自动处理并按照Scheduled中的配置定时执行方法。

但是在启动项目的时候,发生了很诡异的现象,有两个TaskScheduler/ScheduledExecutorService的异常打印了出来。但是系统并没有受影响,依然正常启动,而且定时任务也是正常执行。

2018-09-29 15:54:05,187 DEBUG main org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor [//] Could not find default TaskScheduler bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘org.springframework.scheduling.TaskScheduler‘ available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:996)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.resolveSchedulerBean(ScheduledAnnotationBeanPostProcessor.java:278)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.finishRegistration(ScheduledAnnotationBeanPostProcessor.java:221)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:200)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:94)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at com.cmft.RunApp.main(RunApp.java:34)
2018-09-29 15:54:05,190 DEBUG main org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor [//] Could not find default ScheduledExecutorService bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘java.util.concurrent.ScheduledExecutorService‘ available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:996)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.resolveSchedulerBean(ScheduledAnnotationBeanPostProcessor.java:278)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.finishRegistration(ScheduledAnnotationBeanPostProcessor.java:241)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:200)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:94)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at com.cmft.RunApp.main(RunApp.java:34)
2018-09-29 15:54:05,190 INFO  main org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor [//] No TaskScheduler/ScheduledExecutorService bean found for scheduled processing

二、分析

虽然没有影响系统,但是有异常看着总归很难受,于是尝试去探究下这个异常的原因。

通过观察我们这两个异常是日志模块打印出来的debug级别日志

2018-09-29 15:54:05,187 DEBUG main org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor [//] Could not find default TaskScheduler bean
2018-09-29 15:54:05,190 DEBUG main org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor [//] Could not find default ScheduledExecutorService bean

而且都是在ScheduledAnnotationBeanPostProcessor类中打印出来。看类的名字我们大概能猜到这是@Scheduled注解的处理类。

根据日志内容我们定位到这个问题是由finishRegistration()方法打印出来。

private void finishRegistration() {
        if (this.scheduler != null) {
            this.registrar.setScheduler(this.scheduler);
        }

        if (this.beanFactory instanceof ListableBeanFactory) {
            Map<String, SchedulingConfigurer> configurers = ((ListableBeanFactory)this.beanFactory).getBeansOfType(SchedulingConfigurer.class);
            Iterator var2 = configurers.values().iterator();

            while(var2.hasNext()) {
                SchedulingConfigurer configurer = (SchedulingConfigurer)var2.next();
                configurer.configureTasks(this.registrar);
            }
        }

        if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
            Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");

            try {
                this.registrar.setTaskScheduler((TaskScheduler)this.resolveSchedulerBean(TaskScheduler.class, false));
            } catch (NoUniqueBeanDefinitionException var8) {
                try {
                    this.registrar.setTaskScheduler((TaskScheduler)this.resolveSchedulerBean(TaskScheduler.class, true));
                } catch (NoSuchBeanDefinitionException var7) {
                    if (this.logger.isInfoEnabled()) {
                        this.logger.info("More than one TaskScheduler bean exists within the context, and none is named ‘taskScheduler‘. Mark one of them as primary or name it ‘taskScheduler‘ (possibly as an alias); or implement the SchedulingConfigurer interface and call ScheduledTaskRegistrar#setScheduler explicitly within the configureTasks() callback: " + var8.getBeanNamesFound());
                    }
                }
            } catch (NoSuchBeanDefinitionException var9) {
                this.logger.debug("Could not find default TaskScheduler bean", var9);

                try {
                    this.registrar.setScheduler(this.resolveSchedulerBean(ScheduledExecutorService.class, false));
                } catch (NoUniqueBeanDefinitionException var5) {
                    try {
                        this.registrar.setScheduler(this.resolveSchedulerBean(ScheduledExecutorService.class, true));
                    } catch (NoSuchBeanDefinitionException var4) {
                        if (this.logger.isInfoEnabled()) {
                            this.logger.info("More than one ScheduledExecutorService bean exists within the context, and none is named ‘taskScheduler‘. Mark one of them as primary or name it ‘taskScheduler‘ (possibly as an alias); or implement the SchedulingConfigurer interface and call ScheduledTaskRegistrar#setScheduler explicitly within the configureTasks() callback: " + var5.getBeanNamesFound());
                        }
                    }
                } catch (NoSuchBeanDefinitionException var6) {
                    this.logger.debug("Could not find default ScheduledExecutorService bean", var6);
                    this.logger.info("No TaskScheduler/ScheduledExecutorService bean found for scheduled processing");
                }
            }
        }

        this.registrar.afterPropertiesSet();
    }

看代码我们会发现,spring会从先从注册过的bean中找任务调度器TaskScheduler

 this.registrar.setTaskScheduler((TaskScheduler)this.resolveSchedulerBean(TaskScheduler.class, false));

如果获取不到会抛出异常,然后打印出来

this.logger.debug("Could not find default TaskScheduler bean", var9);

然后继续寻找定时任务的执行类ScheduledExecutorService

this.registrar.setScheduler(this.resolveSchedulerBean(ScheduledExecutorService.class, false));

如果找不到,会继续抛出异常并打印出来

catch (NoSuchBeanDefinitionException var6) {
                    this.logger.debug("Could not find default ScheduledExecutorService bean", var6);
                    this.logger.info("No TaskScheduler/ScheduledExecutorService bean found for scheduled processing");
                }

如此,便看到开头我们看到的两个异常。

看后面代码我们会发现,如果注册的bean中找不到,会调用scheduleTasks()方法初始化TaskScheduler,所以这两个异常并不会影响系统。可能spring 的开发者是想借此提醒开发人员要自己在系统中注册要使用的bean,而不是依赖框架来默认初始化。

解决办法

修改日志级别

第一种是眼不见为净法,简单粗暴地修改日志级别就好。

log4j.logger.org.springframework.scheduling = INFO

这样debug级别的日志就不会被打印出来,只有最后的info级别日志才会被打印。

注册TaskScheduler

既然提示的异常是注册的bean中找不到TaskScheduler,那么我们就注册TaskScheduler。

    @Bean
    public TaskScheduler scheduledExecutorService() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(8);
        scheduler.setThreadNamePrefix("scheduled-thread-");
        return scheduler;
    }

阅读原文

原文地址:https://www.cnblogs.com/MarsCheng/p/9734415.html

时间: 2024-08-03 07:51:44

spring boot.定时任务问题记录(TaskScheduler/ScheduledExecutorService异常)的相关文章

spring boot slf4j日记记录配置详解

转 spring boot slf4j日记记录配置详解 2017年12月26日 12:03:34 阅读数:1219 Spring-Boot--日志操作[全局异常捕获消息处理?日志控制台输出+日志文件记录] 最好的演示说明,不是上来就贴配置文件和代码,而是,先来一波配置文件的注释,再来一波代码的测试过程,最后再出个技术在项目中的应用效果,这样的循序渐进的方式,才会让读者更加清楚的理解一项技术是如何运用在项目中的,虽然本篇很简单,几乎不用手写什么代码,但是,比起网上其他人写的同类型的文章来说,我只能

Spring Boot 报错记录

Spring Boot 报错记录 由于新建的项目没有配置数据库连接启动报错,可以通过取消自动数据源自动配置来解决 解决方案1: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //@SpringBootApplication @MapperScan("com.example.*") //扫描:该包下相应的class,主要是MyBatis的持久化类. 解决方案2: #去配置文件中配置数据库连接参数 #

Spring Boot 之日志记录

Spring Boot 之日志记录 Spring Boot 支持集成 Java 世界主流的日志库. 如果对于 Java 日志库不熟悉,可以参考:细说 Java 主流日志工具库 关键词: log4j, log4j2, logback, slf4j 日志格式 控制台输出 彩色打印 文件输出 日志级别 日志组 日志配置文件 Spring Boot 中的日志配置 源码 引申和引用 Spring Boot 内部日志全部使用 Commons Logging 记录,但保留底层日志实现.为 Java Util

Spring boot学习(六)Spring boot实现AOP记录操作日志

前言 在实际的项目中,特别是管理系统中,对于那些重要的操作我们通常都会记录操作日志.比如对数据库的CRUD操作,我们都会对每一次重要的操作进行记录,通常的做法是向数据库指定的日志表中插入一条记录.这里就产生了一个问题,难道要我们每次在 CRUD的时候都手动的插入日志记录吗?这肯定是不合适的,这样的操作无疑是加大了开发量,而且不易维护,所以实际项目中总是利用AOP(Aspect Oriented Programming)即面向切面编程这一技术来记录系统中的操作日志. 日志分类 这里我把日志按照面向

Spring Boot 定时任务单线程和多线程

Spring Boot 的定时任务: 第一种:把参数配置到.properties文件中: 代码: package com.accord.task; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * 从配置

spring boot 定时任务基于zookeeper的分布式锁实现

基于ZooKeeper分布式锁的流程 在zookeeper指定节点(locks)下创建临时顺序节点node_n 获取locks下所有子节点children 对子节点按节点自增序号从小到大排序 判断本节点是不是第一个子节点,若是,则获取锁:若不是,则监听比该节点小的那个节点的删除事件 若监听事件生效,则回到第二步重新进行判断,直到获取到锁 具体实现 添加Maven依赖: <?xml version="1.0" encoding="UTF-8"?> <

Spring Boot定时任务的使用

Spring Boot中配置定时任务极其简单...... import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.text.SimpleDateFormat

Spring Boot定时任务运行一段时间后自动关闭的解决办法

用Spring Boot默认支持的 Scheduler来运行定时任务,有时在服务器运行一段时间后会自动关闭.原因:Schedule默认是单线程运行定时任务的,即使是多个不同的定时任务,默认也是单线程运行.当线程挂掉时,定时任务也随之终止. 解决方法: 一.改为多线程执行定时任务: 加一个配置类,实现SchedulingConfigurer接口,重写configureTasks方法即可: import org.springframework.context.annotation.Configura

Spring Boot 定时任务 @Scheduled

项目开发中经常需要执行一些定时任务,比如在每天凌晨,需要从 implala 数据库拉取产品功能活跃数据,分析处理后存入到 MySQL 数据库中.类似这样的需求还有许多,那么怎么去实现定时任务呢,有以下几种实现方式. Java 定时任务的几种实现方式 基于 java.util.Timer 定时器,实现类似闹钟的定时任务 使用 Quartz.elastic-job.xxl-job 等开源第三方定时任务框架,适合分布式项目应用 使用 Spring 提供的一个注解: @Schedule,开发简单,使用比