SpringBoot定时任务自动停止关闭

原文链接:https://www.cnblogs.com/bestJavaCoding/p/10623558.html

用Spring Boot默认支持的 Scheduler来运行定时任务,有时在服务器运行一段时间后会自动关闭。原因:Schedule默认是单线程运行定时任务的,即使是多个不同的定时任务,默认也是单线程运行。当线程挂掉时,定时任务也随之终止。

解决方法:

       一.改为多线程执行定时任务:

加一个配置类,实现SchedulingConfigurer接口,重写configureTasks方法即可:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

/**
* 多线程执行定时任务
@author DaiMaTanQi
* 2019年3月28日
*/
@Configuration
//用线程池给不同定时任务分配不同的线程
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//设定一个长度10的定时任务线程池
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}

 

复制代码
@Scheduled(cron="0/1 * * * * ? ") //每1秒执行一次
 
public void testCron1() {
 
          DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
          logger.info(sdf.format(new Date())+"*********每1秒执行一次");
 
}
 
 
 
@Scheduled(cron="0/2 * * * * ? ") //每2秒执行一次
 
public void testCron2() {
 
          DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
          logger.info(sdf.format(new Date())+"*********每2秒执行一次");
 
}
 
 
@Scheduled(cron="0/3 * * * * ? ") //每3秒执行一次
 
public void testCron3() {
 
          DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
          logger.info(sdf.format(new Date())+"*********每3秒执行一次");
 
}
复制代码

 

 

二.线程挂掉的原因主要有两个,一是运行时抛出异常未被捕获,二是调用外部接口时,http请求超时。

解决办法:在方法最后捕获所有异常,http请求设置超时时间:

connection.setConnectTimeout(30000);

connection.setReadTimeout(60000);

 

绝大部分定时任务挂掉情况可以通过以上方式解决,如果解决不了,建议把需要定时运行的任务写成接口,用linux服务器的crontab定时调用。

posted @   枫树湾河桥  阅读(10680)  评论(2编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
Live2D
欢迎阅读『SpringBoot定时任务自动停止关闭』
西雅图
17:15发布
西雅图
17:15发布
6°
东北风
2级
空气质量
相对湿度
86%
今天
多云
3°/15°
周四
4°/16°
周五
4°/14°
点击右上角即可分享
微信分享提示