我的代码
/**
* Author:Mr.X
* Date:2017/10/30 14:54
* Description:
*/
@Component
@Configurable
@EnableScheduling
public class ScheduledTasksConfig {
@Autowired
private WeixinConfig weixinConfig;
@Autowired
private UserWebAnalysisRepository userWebAnalysisRepository;
/**
* 每隔110分钟刷新一次access_token和jsapi_ticket
* 7200秒=2小时
*/
@Scheduled(fixedRate = 1000 * 7200)
private void getAccessTokenAndJsapiTicket() {
// 1、获取accessToken
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + weixinConfig.getAppID() + "&secret=" + weixinConfig.getAppSecret();
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(accessTokenUrl, String.class);
JSONObject jsonObj = JSON.parseObject(response);
String accessToken = jsonObj.getString("access_token");
System.out.println("定时任务获取access_token--->" + accessToken);
WebConst.ACCESS_TOKEN = accessToken; // 缓存accessToken
// 2、根据accessToken获取jsapi_ticket
String ticketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
response = restTemplate.getForObject(ticketURL, String.class);
jsonObj = JSON.parseObject(response);
String jsapi_ticket = jsonObj.getString("ticket");
System.out.println("定时任务获取jsapi_ticket--->" + jsapi_ticket);
WebConst.JSAPI_TICKET = jsapi_ticket; // 缓存jsapi_ticket
}
/**
* 每天23点将微信端关注用户增减信息更新进库
*/
@Scheduled(cron = "0 0 23 * * ?")
private void getUserSource() {
String url = "https://api.weixin.qq.com/datacube/getusercumulate?access_token=" + WebConst.ACCESS_TOKEN;
RestTemplate restTemplate = new RestTemplate();
String jsonStr = "{ \n" +
" \"begin_date\": \"" + DateUtil.format(new Date(), "yyyy-MM-dd") + "\", \n" +
" \"end_date\": \"" + DateUtil.format(new Date(), "yyyy-MM-dd") + "\"\n" +
"}";
String response = restTemplate.postForObject(url, jsonStr, String.class);
JSONObject jsonObj = JSON.parseObject(response);
String ref_date = jsonObj.getString("ref_date");
String user_source = jsonObj.getString("user_source");
String new_user = jsonObj.getString("new_user");
String cancel_user = jsonObj.getString("cancel_user");
UserWebAnalysis userWebAnalysis = new UserWebAnalysis();
userWebAnalysis.setRefDate(new Date());
userWebAnalysis.setUserSource(Integer.valueOf(user_source));
userWebAnalysis.setNewUser(Integer.valueOf(new_user));
userWebAnalysis.setCancelUser(Integer.valueOf(cancel_user));
userWebAnalysisRepository.save(userWebAnalysis);
}
}
参考链接
http://www.jianshu.com/p/ef18af5a9c1d