ScheduledExecutorService定时任务请求天气预报

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定时任务请求天气预报)