前面博客{定时JOB,去请求数据,并找出最新数据持久化}的有关问题
前面博客{定时JOB,去请求数据,并找出最新数据持久化}的问题
之前的博客 定时JOB,去请求数据,并找出最新数据持久化 ,代码是有问题的、不够严谨的。
存在两个问题:1、HttpClient 是new出来的,这样会导致oom的,比如spring mvc 就是单例的(他的线程安全问题暂不提)。2、job执行时间大于间隔时间的问题,当执行时间 大于 间隔时间, JOB会默认启新线程来执行JOB,这样也会有线程问题,我这里的共享变量是最大时间,会有线程安全问题的。如果我不同步,只有用其他方法。
解决:1、把HttpClient 全部改为静态方法。2、不采用同步,简单的在JOB上加@DisallowConcurrentExecution,用于阻止并发。
代码:
//阻止并发,防止maxBjsj混乱 @DisallowConcurrentExecution public class AlarmJob implements Job { public static AtomicReference<Date> maxBjsj ; static{ if(CacheUtils.get(Contants.jq_maxDateCache, Contants.jq_maxDate_key) == null){ maxBjsj = new AtomicReference<Date>(); }else{ maxBjsj = (AtomicReference<Date>)CacheUtils.get(Contants.jq_maxDateCache, Contants.jq_maxDate_key); } } public static int count = 0; //可以缓存到内存 // @Cacheable(value="sysCache" ) @Override public void execute(JobExecutionContext context) throws JobExecutionException { String url = Contants.alarm_url+DateUtils.getDate("yyyyMMdd"); try { long t1 = System.currentTimeMillis(); // 排序前取得当前时间 if(HttpClient.get(url,maxBjsj,Contants.TYPE_JQ)){ // if(new HttpClient().get(url,maxBjsj,Contants.TYPE_JQ)){ long t2 = System.currentTimeMillis(); // 排序后取得当前时间 Calendar c = Calendar.getInstance(); c.setTimeInMillis(t2 - t1); System.out.println("----第"+ ++count +"次 同步结束----"+"耗时: " + c.get(Calendar.MINUTE) + "分 " + c.get(Calendar.SECOND) + "秒 " + c.get(Calendar.MILLISECOND) + " 毫秒"); } // } catch (Exception e) { e.printStackTrace(); } } }
refs: http://www.cnblogs.com/wynn0123/archive/2015/07/14/4646206.html
http://blog.****.net/pdw2009/article/details/50195639