错误复现
在启动类中添加注解 @EnableScheduling
然后编写定时任务
@Component
@Slf4j
public class Task{
/**
* 每天晚上0点执行
*/
//@Scheduled(cron = "0 0 0 * * ? ")
@Scheduled(cron = "0/3 * * * * ?")
public void documentAutoDelete(){
log.info("定时任务开始执行--------->"+Thread.currentThread());
// todo
log.info("定时任务执行结束--------->"+Thread.currentThread());
}
}
启动报错,错误日志如下
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled.
2021-07-19 15:50:51.725 ERROR 52692 --- [main] o.s.boot.SpringApplication: Application run failed
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named
'defaultSockJsTaskScheduler' is expected to be of type
'org.springframework.scheduling.TaskScheduler' but was actually of type 'org.springframework.beans.factory.support.NullBean'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
(AbstractBeanFactory.java:395) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
错误排查
因为我们使用了websocket @EnableWebSocket,
在springboot中不能同时使用websocket和spring的定时注解 ,同时使用就会报错。
因为报错说缺少了一个任务调度器,其实是冲突了找不到,我们可以手动注入一个调度器bean,即可解决
添加配置类
@Configuration
public class TaskConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduling = new ThreadPoolTaskScheduler();
scheduling.setPoolSize(15);
scheduling.initialize();
return scheduling;
}
}
添加配置类后,配置文件相关配置就会失效
总之yml和config二选一
spring:
task:
scheduling:
pool:
size: 10
运行发现 项目正常允许 定时任务开始执行
2021-07-19 16:01:51.017 INFO 23516 --- [taskScheduler-1] c.n.l.task.DocumentAutoDelete:
定时任务执行结束--------->Thread[taskScheduler-1,5,main]
2021-07-19 16:01:54.015 INFO 23516 --- [taskScheduler-2] c.n.l.task.DocumentAutoDelete:
定时任务开始执行--------->Thread[taskScheduler-2,5,main]