Android Timer和TimerTask
以下内容根据 The JavaTM Tutorial 和相关API doc翻译整理,以供日后参考:
1.概览
Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
简单的一个例程:
mport java.util.Timer;
import java.util.TimerTask; /**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/ public class Reminder {
Timer timer; public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*);
} class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
} public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder();
System.out.println("Task scheduled.");
}
}
运行这个小例子,你会首先看到:
About to schedule task.
5秒钟之后你会看到:
Time's up!
这个小例子可以说明一些用Timer线程实现和计划执行一个任务的基础步骤:
- 实现自定义的TimerTask的子类,run方法包含要执行的任务代码,在这个例子里,这个子类就是RemindTask。
- 实例化Timer类,创建计时器后台线程。
- 实例化任务对象 (
new RemindTask()). - 制定执行计划。这里用schedule方法,第一个参数是TimerTask对象,第二个参数表示开始执行前的延时时间(单位是milliseconds,这里定义了5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在11:01 p.m.执行:
//Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, );
calendar.set(Calendar.MINUTE, );
calendar.set(Calendar.SECOND, );
Date time = calendar.getTime(); timer = new Timer();
timer.schedule(new RemindTask(), time);
2.终止Timer线程
默认情况下,只要一个程序的timer线程在运行,那么这个程序就会保持运行。当然,你可以通过以下四种方法终止一个timer线程:
- 调用timer的cancle方法。你可以从程序的任何地方调用此方法,甚至在一个timer task的run方法里。
- 让timer线程成为一个daemon线程(可以在创建timer时使用new Timer(true)达到这个目地),这样当程序只有daemon线程的时候,它就会自动终止运行。
- 当timer相关的所有task执行完毕以后,删除所有此timer对象的引用(置成null),这样timer线程也会终止。
- 调用System.exit方法,使整个程序(所有线程)终止。
Reminder的例子使用了第一种方式。在这里不能使用第二种方式,因为这里需要程序保持运行直到timer的任务执行完成,如果设成daemon,那 么当main线程结束的时候,程序只剩下timer这个daemon线程,于是程序不会等timer线程执行task就终止了。
有些时候,程序的终止与否并不只与timer线程有关。举个例子,如果我们使用AWT来beep,那么AWT会自动创建一个非daemon线程来保持程序 的运行。下面的代码我们对Reminder做了修改,加入了beeping功能,于是我们需要加入System.exit的调用来终止程序。
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit; /**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/ public class ReminderBeep {
Toolkit toolkit;
Timer timer; public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds*);
} class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(); //Stops the AWT thread (and everything else)
}
} public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep();
System.out.println("Task scheduled.");
}
}
3.反复执行一个任务
先看一个例子:
public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(),
, //initial delay
*); //subsequent rate
}
class RemindTask extends TimerTask {
int numWarningBeeps = ;
public void run() {
if (numWarningBeeps > ) {
toolkit.beep();
System.out.println("Beep!");
numWarningBeeps--;
} else {
toolkit.beep();
System.out.println("Time's up!");
//timer.cancel(); //Not necessary because we call System.exit
System.exit(); //Stops the AWT thread (and everything else)
}
}
}
...
}
执行,你会看到如下输出:
Task scheduled.
Beep!
Beep! //one second after the first beep
Beep! //one second after the second beep
Time's up! //one second after the third beep
这里使用了三个参数的schedule方法用来指定task每隔一秒执行一次。如下所列为所有Timer类用来制定计划反复执行task的方法 :
schedule(TimerTask task, long delay, long period)schedule(TimerTask task, Date time, long period)scheduleAtFixedRate(TimerTask task, long delay, long period)scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
当计划反复执行的任务时,如果你注重任务执行的平滑度,那么请使用schedule方法,如果你在乎的是任务的执行频度那么使用 scheduleAtFixedRate方法。 例如,这里使用了schedule方法,这就意味着所有beep之间的时间间隔至少为1秒,也就是说,如果有一个beap因为某种原因迟到了(未按计划执 行),那么余下的所有beep都要延时执行。如果我们想让这个程序正好在3秒以后终止,无论哪一个beep因为什么原因被延时,那么我们需要使用 scheduleAtFixedRate方法,这样当第一个beep迟到时,那么后面的beep就会以最快的速度紧密执行(最大限度的压缩间隔时间)。
4.进一步分析schedule和scheduleAtFixedRate
(1)2个参数的schedule在制定任务计划时, 如果指定的计划执行时间 scheduledExecutionTime<=systemCurrentTime,则task会被立即执行。 scheduledExecutionTime不会因为某一个task的过度执行而改变。
(2)3
个参数的schedule在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间随着前一次的实际执行时间而变,也就是
scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是说如果第n
次执行task时,由于某种原因这次执行时间过长,执行完后的
systemCurrentTime>=scheduledExecutionTime(第n+1次),则此时不做时隔等待,立即执行第n+1次
task,而接下来的第n+2次task的scheduledExecutionTime(第n+2次)就随着变成了
realExecutionTime(第n+1次)+periodTime。说白了,这个方法更注重保持间隔时间的稳定。
(3)3个参数的scheduleAtFixedRate
在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间在最初就被定下来了,也就是
scheduledExecutionTime(第n次)=firstExecuteTime+n*periodTime;如果第n次执行task时,由
于某种原因这次执行时间过长,执行完后的systemCurrentTime>=scheduledExecutionTime(第n+1次),则
此时不做period间隔等待,立即执行第n+1次task,而接下来的第n+2次的task的scheduledExecutionTime(第n+2
次)依然还是firstExecuteTime+(n+2)*periodTime这在第一次执行task就定下来了。说白了,这个方法更注重保持执行频率的稳定。
5.一些注意的问题
- 每一个Timer仅对应唯一一个线程。
- Timer不保证任务执行的十分精确。
- Timer类的线程安全的。
Android Timer和TimerTask的更多相关文章
- android Timer and TImerTask
android Timer and TImerTask Caused by: java.lang.IllegalStateException: TimerTask is scheduled alrea ...
- Android简易实战教程--第四十八话《Android - Timer、TimerTask和Handler实现倒计时》
之前本专栏文章中的小案例有写到:第三十九话<Chronometer实现倒计时> 以及使用异步实现倒计时:第三十三话< AsyncTask异步倒计时> 本篇文章 结合Timer. ...
- android Timer与TimerTask的相关操作
项目上面的部分操作需要使用到定时器进行周期性的控制.网络上面对于定时器的操作通常有三种实现方法. 我是通过Timer与TimerTask相结合实现的定时器功能.具体实现过程如下: 第一步,得到Time ...
- Java中的Timer和TimerTask在Android中的用法(转)
转自:http://blog.csdn.net/zuolongsnail/article/details/8168689 在开发中我们有时会有这样的需求,即在固定的每隔一段时间执行某一个任务.比如UI ...
- Android 开发 重写定位器类Timer与TimerTask
class AttendanceTimer extends Timer { private static final int LOCATION = 0x01; private static final ...
- android,结合Timer和TimerTask实现定时任务
当我们需要每隔一段时间执行一个任务的时候,就需要使用TimerTask了,下面是入门的例子, 值得注意的是Timer.TimerTask,cancel之后就需要重新声明一个对象,否则会报错的哦~ pa ...
- android Timer TimerTask用法笔记
Android中经常会遇到执行一些周期性定时执行的任务.初学的时候经常会使用Thread.sleep()方法.在android中,有Timer可以专门干这个事情. 先看看Timer.class中都是些 ...
- Android Timer 的 schedule()方法定时循环切换图片
void java.util.Timer.schedule(TimerTask task, long delay, long period)第一个参数,是 TimerTask 类,在包:import ...
- Java并发编程:Timer和TimerTask(转载)
Java并发编程:Timer和TimerTask(转载) 下面内容转载自: http://blog.csdn.net/xieyuooo/article/details/8607220 其实就Timer ...
随机推荐
- 基础篇:1)时代的发展与结构设计--3d与2d设计的变迁
本章目的:机械设计需要追寻时代的脚步. 1.机械作图时代的划分 这张图是作者个人对机械作图发展的简单划分,并非哪个网站的数据.所以粗糙或错误请海涵. 2.2d作图时代 纯2d时代中,工程师开只绘制二维 ...
- &与&& ,|与||的区别
&&和||是短路运算符,&和|是非短路运算符 &&与& 区别:两者都表示“与”运算,但是&&运算符第一个表达式不成立的话,后面的表达式不 ...
- 编译安装php-5.3.27报错:make: *** [sapi/fpm/php-fpm] 错误 1
安装PHP的时候make报错:make: *** [sapi/fpm/php-fpm] Error 1 原因:Centos6.8之后已经将iconv库加进来了,如果再安装libiconv库相当于重复一 ...
- rabbitmq 消息确认
消息确认主要用在接收方 如果接收方没有确认, broker可以重发,确保消息至少消息一次..
- 《Paxos Made Simple》翻译(转)
1 Introduction 可能是因为之前的描述对大多数读者来说太过Greek了,Paxos作为一种实现容错的分布式系统的算法被认为是难以理解的.但事实上,它可能是最简单,最显而易见的分布式算法了. ...
- 怎么在vue中引入layui
新项目想用layui框架,学习了把前辈是怎么引入layui的,这里记录下 1.index.html要引入layui.js文件 <script src="/static/layui/la ...
- Angular 2 升级到 Angular 5
Angular 2 升级到 Angular 5 ts文件最上面的import语句里不要添加 .ts 后缀 , 不然 npm start 编译会失败 . 虽然浏览器能打开项目的URL , 但是内容会丢失 ...
- 转: 将Eclipse代码导入到AndroidStudio的两种方式 ,测试了方法2,成功。
蛋疼,不知道为什么我的eclipse的logcat总是莫名其妙的显示一堆黄色字体的字,看不懂的那种,如下图: 然后查了一下资料,说可能是adt版本太低,手机系统太高. 然后本来想升级adt,但是各种折 ...
- 宜人贷项目里-----正则匹配input输入月份规则
在标签上可以直接进行校验如下,如果只调数字键盘type=number不好用可以用type=tel <input name="creditDate" oninput=" ...
- 什么是DDL,DCL,DML
1.DCL 数据库控制语言,全称是Data Control Language 关键字类型:grant.remove 2.DDL 数据库定义语言,全称是Data Definition Language ...