定时任务代码示例
@Slf4j
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class ReactorScheduleTask{
@Scheduled(fixedRate=1000)
public void reactorColumnExperiment() throws Exception {
//long startTime = System.currentTimeMillis();
//log.info("----------------------run time :" + (System.currentTimeMillis() - startTime) + "ms");
}
问题:在测试环境中,发现执行一段时间后,定时任务不执行了。
原因分析:请求某些接口响应不稳定,client端的请求线程一直等待不会释放,如果任务的线程池中的线程,就会一直占用线程池资源,导致线程池不能响应后续的的任务。
解决方案:设置client超时时间,超时不响应直接抛出,等待下一次执行
这里是HttpClient 4.3版本
/**
* get请求
*
* @return
*/
public static CallbackResult doGet(String url, Map<String, String> headers) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-Type", "application/json");
//设置超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300).setConnectTimeout(300).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
return new CallbackResult().alert(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}