美文网首页
ScheduledExecutorService定时任务请求天气

ScheduledExecutorService定时任务请求天气

作者: 空格键_尘 | 来源:发表于2019-01-28 16:35 被阅读0次
    package zjc.getWeather;
    
    import java.util.concurrent.Executors;
    
    import java.util.concurrent.ScheduledExecutorService;
    
    import java.util.concurrent.TimeUnit;
    
    public class GetWeather {
    
        private static volatile GetWeathersingleton;
    
        private GetWeather() {}
    
        public static GetWeathergetInstance() {
    
            if (singleton ==null) {
    
                synchronized (GetWeather.class) {
    
                    if (singleton ==null) {
    
                        singleton =new GetWeather();
    
                      }
    
                }
    
            }
    
            return singleton;
    
      }
    
    //定时执行的间隔时间,不得小于等于0, 此次间隔30分钟请求一次
    
    private final static IntegercacheTime =1800;
    
    //首次执行的延时时间,不得小于等于0, 一秒后开始请求
    
    private final static IntegerinitDelay =1;
    
    public void getWeather(){
    
    Runnable runnable =new Runnable() {
    
        public void run() {
    
                    // 海口市天气预报码:101310101
    
                    String s = PureNetUtil.get("http://t.weather.sojson.com/api/weather/city/101310101");
    
                    System.out.println(s);
    
         }
    
    };
    
            ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    
            // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
    
            service.scheduleAtFixedRate(runnable, initDelay, cacheTime, TimeUnit.SECONDS);
    
        }
    
    }
    

    相关文章

      网友评论

          本文标题:ScheduledExecutorService定时任务请求天气

          本文链接:https://www.haomeiwen.com/subject/mdnajqtx.html