Spring 定时任务

最近写一个功能 ,需要定时去调用平台接口

一 、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 、结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值