3种计时器实现方法

目标:每隔一秒,发送一个事件

1.Timer


    @Override
    public void onDestroy() {
        LogUtil.print("");
        timer.cancel();
        super.onDestroy();
    }

    /**
     * 初始化
     */
    private void init() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //发送事件:Thread=Timer-0
                sendUpdateTimeEvent();
            }
        }, 1000, 1000);
    }

2.RxJava


    @Override
    public void onDestroy() {
        LogUtil.print("");
        subscription.unsubscribe();
        super.onDestroy();
    }

    /**
     * 初始化
     */
    private void init() {
        subscription = Observable.interval(1000, 1000, TimeUnit.MILLISECONDS)
                .subscribe(time -> {
                    //发送事件:Thread=RxComputationScheduler-1
                    sendUpdateTimeEvent();
                });
    }

3.Handler


    @Override
    public void onDestroy() {
        LogUtil.print("");
        handler.removeCallbacks(runnable);
        super.onDestroy();
    }

    Handler handler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //发送事件:Thread=main
            sendUpdateTimeEvent();
            handler.postDelayed(this, 1000);
        }

    };

    /**
     * 初始化
     */
    private void init() {
        runnable.run();
    }
2016-10-29 13:4242