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 @ 2020-03-11 18:30  枫树湾河桥  阅读(10336)  评论(2编辑  收藏  举报
Live2D