首页 > 编程语言 > 详细

SpringBoot定时任务自动停止关闭

时间:2020-03-11 19:21:54      阅读:498      评论:0      收藏:0      [点我收藏+]

原文链接: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定时调用。

SpringBoot定时任务自动停止关闭

原文:https://www.cnblogs.com/fswhq/p/12464491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!