• 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定时调用。

  • 相关阅读:
    Python 数据类型:字典
    .Net开发工程师工具箱
    Javascript事件设计模式(七)
    LINQ学习之旅 (四)
    JavaScript实现抽象类与虚方法(六)
    Javascript中的反射机制(五)
    Javascript中类的实现机制(四)
    Javascript中的函数(三)
    Javascript面向对象基础(二)
    Web应用程序项目XXXX已配置为使用IIS。无法访问IIS 元数据库。您没有足够的特权访问计算机上的IIS
  • 原文地址:https://www.cnblogs.com/fswhq/p/12464491.html
Copyright © 2020-2023  润新知