java方法计时器,懒汉式,转换为00:00:00格式

计时器工具:

public class TimingUtil {

    private static TimingUtil mTimingUtil;

    private Timer timer;

    private TimingCallback mTimingCallback;

    private int mHeartbeat = 0;

    private TimingTask mTimerTask;

    private TimingUtil() {}

    //初始化

    public static TimingUtil init() {

        if (mTimingUtil == null) {

            mTimingUtil = new TimingUtil();

        }

        return mTimingUtil;

    }

    //开始

    public void startTiming() {

        if (mTimerTask != null) {

            return;

        }

        mTimerTask = new TimingTask();

        timer = new Timer();

        timer.schedule(mTimerTask, 0, 1000);

    }

    public void setListen(TimingCallback timingCallback) {

        mTimingCallback = timingCallback;

        mTimingCallback.heartbeat(intToDateString(mHeartbeat));

    }

    //暂停

    public void suspend() {

        mTimerTask.cancel();

        mTimerTask = null;

    }

    //停止清空

    public void cancel() {

        timer.cancel();

        if (mTimerTask!=null) {

            mTimerTask.cancel();

            mTimerTask = null;

        }

        mHeartbeat = 0;

    }

    private class TimingTask extends TimerTask {

        @Override

        public void run() {

            if (mTimingCallback==null){

                return;

            }

            mTimingCallback.heartbeat(intToDateString(mHeartbeat++));

        }

    }

    private String intToDateString(int value) {

        int hour = value / 3600;

        int min = value / 60 % 60;

        int second = value % 60;

        String hourString;

        String minString;

        String secondString;

        if (hour < 10) {

            hourString = "0" + hour;

        } else {

            hourString = hour + "";

        }

        if (min < 10) {

            minString = "0" + min;

        } else {

            minString = min + "";

        }

        if (second < 10) {

            secondString = "0" + second;

        } else {

            secondString = second + "";

        }

        return hourString + ":" + minString + ":" + secondString;

    }

}


接口:

public interfaceTimingCallback{

public voidheartbeat(Stringtiming);

}

你可能感兴趣的:(java方法计时器,懒汉式,转换为00:00:00格式)