/**
 * <p>Copyright:Copyright(c) 2017</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>包名:com.cesgroup.cesmonitor</p>
 * <p>文件名:Test.java</p>
 * <p>创建时间:2017年7月5日 下午5:42:13</p>
 * <p>作者:zhang.erwei</p>
 */

package com.cesgroup.cesmonitor;

import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年7月5日
 */
public class Test {

    int i = 0;

    public static Test t = new Test();

    public static Test getInstance() {
        return t;
    }

    private String accessToken = null;

    /**
     * @param args
     */
    public static void main(String[] args) {

        while (true) {
            new Thread() {

                @Override
                public void run() {
                    System.out.println("main:" + Test.getInstance().getAccessToken());
                }
            }.start();

            try {
                Thread.sleep(20000L);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private synchronized void loadAccessToken(final String url) {
        System.out.println("loadAccessToken");
        try {
            accessToken = "token:" + i++;
            Integer expiresIn = 20;
            if (accessToken != null && expiresIn != null) {
                //定时获取下次
                if (expiresIn > 10) {
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {

                        @Override
                        public void run() {
                            loadAccessToken(url);
                        }
                    }, (expiresIn - 10) * 1000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取微信连接的access_token
     *
     * @return access_token
     */
    public String getAccessToken() {
        if (accessToken == null) {
            loadAccessToken(null);
        }
        return accessToken;
    }

}
