Notice: 函数 WP_Scripts::localize 的调用方法不正确$l10n 参数必须是一个数组。若要将任意数据传递给脚本,请改用 wp_add_inline_script() 函数。 请查阅调试 WordPress来获取更多信息。 (这个消息是在 5.7.0 版本添加的。) in /data/www/appblog/wp-includes/functions.php on line 6131

Spring Boot定时任务运行一段时间后自动关闭的解决办法

使用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;

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

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

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

connection.setConnectTimeout(30000);

connection.setReadTimeout(60000);

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

上一篇 Spring Boot 中的 RestTemplate不好用?试试 Retrofit!
下一篇 Spring Boot 发布回滚