TimerTask的使用

在开发中我们有时会有这样的需求,即在固定的每隔一段时间执行某一个任务。比如UI上的控件需要随着时间改变,我们可以使用Java为我们提供的计时器的工具类,即Timer和TimerTask。 

Timer是一个普通的类,其中有几个重要的方法;而TimerTask则是一个抽象类,其中有一个抽象方法run(),类似线程中的run()方法,我们使用Timer创建一个他的对象,然后使用这对象的scheduleAtFixedRate方法来完成这种间隔的操作。

schedule() 和 scheduleAtFixedRate() 的区别

1.  schedule() ,2个参数方法:
在执行任务时,如果指定的计划执行时间scheduledExecutionTime <= systemCurrentTime,则task会被立即执行。

2.  schedule() ,3个参数方法:
在执行任务时,如果指定的计划执行时间scheduledExecutionTime <= systemCurrentTime,则task会被立即执行,之后按period参数固定重复执行。

3.  scheduleAtFixedRate() ,3个参数方法:
在执行任务时,如果指定的计划执行时间scheduledExecutionTime<= systemCurrentTime,则task会首先按执行一次;然后按照执行时间、系统当前时间和period参数计算出过期该执行的次数,计算按照: (systemCurrentTime-scheduledExecutionTime)/period,再次执行计算出的次数;最后按period参数固定重复执行。

4.  schedule() 和scheduleAtFixedRate() 
schedule()方法更注重保持间隔时间的稳定。
scheduleAtFixedRate()方法更注重保持执行频率的稳定。


TimerTask task = new TimerTask() {
            @Override
            public void run() {

                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {  }
                });

            }
        };



mTimer = new Timer();
 mTimer.scheduleAtFixedRate(task, 2000, 5000);







你可能感兴趣的:(TimerTask的使用)