最近写一个功能 ,需要定时去调用平台接口
一 、xml 里添加定时器配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd" default-autowire="byName">
<!-- 定时器配置 -->
<!-- 开启这个配置,spring才能识别@Scheduled注解 -->
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" pool-size="10"/>
<!-- 扫描门店的激活状态,到期后自动设置为未激活状态 -->
<bean class="com.souche.rpa.task.RpaTask" id="rpaTask"/>
</beans>
二 、在代码里 ,利用@Scheduled注解 和cron表达式 实现每隔五秒去调用一次接口
package com.souche.rpa.task;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.souche.rpa.service.RpaService;
import com.souche.rpa.util.HttpSenderUtils;
import com.souche.rpa.vo.ParamVO;
/**
* @description 定时扫描开放平台接口
* @author sxl
* @date 2019/04/01
*/
@Component
public class RpaTask {
private Logger logger = LoggerFactory.getLogger(RpaTask.class);
@Autowired
private RpaService rpaService;
/**
* @Description: 调用开发平台接口
* @author: sxl
* @date: 2019/04/02
*/
@Scheduled(cron = "0/5 * * * * ?")
public void scanOpenApi() {
String url = "http://openapi.proxy.dasouche.com/v3";
ParamVO vo = new ParamVO();
vo.setAppKey("sanhuan.com");
vo.setTimestamp(System.currentTimeMillis());
vo.setApi("com.souche.messagefetchdev.v1.message.izayoiCompanyCode");
logger.info("请求参数:{}", JSON.toJSONString(vo));
try {
JSONObject doPostStr = HttpSenderUtils.doPostStr(url, JSON.toJSONString(vo));
logger.info("接口返回数据:{}", doPostStr);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3 、结果