于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应运行的次数,再去按设定频率去运行。
版权声明:本文博主原创文章,博客,未经同意,不得转载。