在android中调度定时任务有两种方法
1.schedule
2.scheduleAtFixedRate
这两种方法的区别在于 首次调用时间(Date when)这个参数
<span style="font-family:SimHei;font-size:14px;"> // TimerTask
task = new TimerTask() {
@Override
public void run() {
// 输出当前毫秒为单位的时间
Log.i("Test", ">>>" + System.currentTimeMillis());
}
};
// 获取毫秒为单位的当前时间
long crt = System.currentTimeMillis();
timer = new Timer();
// 调度,以当前毫秒时间减10秒
// timer.schedule(task, new Date(crt - 10 * 1000), 2000);
timer.scheduleAtFixedRate(task, new Date(crt - 10 * 1000), 2000);</span>
schedule调度不会去计算首次调用时间 它会立即调用一次 在之后每2秒调用一次
scheduleAtFixedRate 调度则会计算首次调用时间,由于我们首次调用时间设置为当前时间减10秒,那么在执行时会先计算出这10秒内应task应执行的次数,再去按设定频率去执行。