`
kanwoerzi
  • 浏览: 1645066 次
文章分类
社区版块
存档分类
最新评论

Timer技术

 
阅读更多
ClassOverview
java.util.Timerareusedtoschedulejobsforexecutioninabackgroundprocess.
Asinglethreadisusedfortheschedulingandthisthreadhastheoptionofbeingadaemonthread.
BycallingcancelyoucanterminateaTimeranditsassociatedthread.

Alltaskswhicharescheduledtorunafterthispointarecancelled.
Tasksareexecutedsequentiallybutaresubjecttothedelaysfromothertasksrunmethods.
Ifaspecifictasktakesanexcessiveamountoftimetorunitmayimpactthetimeatwhichsubsequenttasksmayrun.
TheTimerTaskdoesnotofferanyguaranteesaboutthereal-timenatureofschedulingtasks
asitsunderlyingimplementationreliesontheObject.wait(long)method.
MultiplethreadscanshareasingleTimerwithouttheneedfortheirownsynchronization.

ATimercanbesettoscheduletaskseitheratafixedrateorwithafixedperiod.
Fixed-periodexecutionisthedefault.
Thedifferencebetweenfixed-rateandfixed-periodexecutionisthefollowing:Withfixed-rateexecution,
thestarttimeofeachsuccessiverunofthetaskisscheduledinabsolutetermswithoutregardforwhentheprevioustaskrunactuallytookplace.
Thiscanresultinaseriesofbunched-upruns(onelaunchedimmediatelyafteranother)
ifbusyresourcesorothersystemdelayspreventtheTimerfromfiringforanextendedtime.
Withfixed-periodexecution,eachsuccessiverunofthetaskisscheduledrelativetothestarttimeofthepreviousrunofthetask,
sotworunsofthetaskareneverfiredclosertogetherintimethanthespecifiedperiod.

Timers主要是用来在后台运行一些任务。可以把Timer设置为守护线程。当调用cancel时所有已经安排的任务都没会被取消。
Timer中的任务是依次执行的,如果一个任务花很长时间才执行完,那么它就可能影响下一个任务的开始执行的时间。
TimerTask对任务的实时调度并没有保证,因为作为底层的实现依赖于Object.wait(long)方法。
注意:守护线程就是一直运行,即使任务完成也不会停止的线程。详细内容请参考《守护线程
构造函数
Public Constructors
<nobr style="line-height:21px"></nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#Timer(java.lang.String,%20boolean)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Timer</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/lang/String.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">String</a>name, boolean isDaemon)</nobr>
Creates a new namedTimerwhich may be specified to be run as a daemon thread.
<nobr style="line-height:21px"></nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#Timer(java.lang.String)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Timer</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/lang/String.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">String</a>name)</nobr>
Creates a new namedTimerwhich does not run as a daemon thread.
<nobr style="line-height:21px"></nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#Timer(boolean)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Timer</a></span>(boolean isDaemon)</nobr>
Creates a newTimerwhich may be specified to be run as a daemon thread.
<nobr style="line-height:21px"></nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#Timer()" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Timer</a></span>()</nobr>
Creates a new non-daemonTimer.
主要方法

Public Methods
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#cancel()" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">cancel</a></span>()</nobr>
Cancels theTimerand all scheduled tasks.
<nobr style="line-height:21px">int</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#purge()" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">purge</a></span>()</nobr>
Removes all canceled tasks from the task queue.
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask,%20java.util.Date,%20long)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">schedule</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task,<a rel="nofollow" href="http://developer.android.com/reference/java/util/Date.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Date</a>when, long period)</nobr>
Schedule a task for repeated fixed-delay execution after a specific time has been reached.
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask,%20long,%20long)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">schedule</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task, long delay, long period)</nobr>
Schedule a task for repeated fixed-delay execution after a specific delay.
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask,%20java.util.Date)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">schedule</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task,<a rel="nofollow" href="http://developer.android.com/reference/java/util/Date.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Date</a>when)</nobr>
Schedule a task for single execution.
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask,%20long)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">schedule</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task, long delay)</nobr>
Schedule a task for single execution after a specified delay.
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">scheduleAtFixedRate</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task, long delay, long period)</nobr>
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
delay时间后开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。
<nobr style="line-height:21px">void</nobr> <nobr style="line-height:21px"><span style="line-height:21px; margin-right:2px"><a rel="nofollow" href="http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20java.util.Date,%20long)" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">scheduleAtFixedRate</a></span>(<a rel="nofollow" href="http://developer.android.com/reference/java/util/TimerTask.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">TimerTask</a>task,<a rel="nofollow" href="http://developer.android.com/reference/java/util/Date.html" style="color:rgb(0,102,153); line-height:21px; text-decoration:none">Date</a>when, long period)</nobr>
Schedule a task for repeated fixed-rate execution after a specific time has been reached.
when时间开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。
Timer有两种调度模式fixed-rate(固定调度周期模式),fixed-period(完整执行周期模式)。默认的是fixed-period。
fixed-period
publicvoidschedule(TimerTasktask,longdelay,longperiod)
Scheduleataskforrepeatedfixed-delayexecutionafteraspecificdelay. schedule(TimerTasktask,Datewhen,longperiod)
在delay时间后开始执行第一次,从此以后每隔period又开始执行。如果时间到了,但是当前还有其他的任务在执行,
它只有等当前任务执行完了,才能被调度并执行。

fixed-rate:
publicvoidscheduleAtFixedRate(TimerTasktask,longdelay,longperiod)
public voidscheduleAtFixedRate(TimerTasktask,Datewhen,longperiod)
在delay时间后开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。

因为Timer本身自己是新开了一个线程的,所以为了线程安全,不要在他里面做UI方面的操作。如果需要做UI的话,请通过一个Handler来在UI线程中来进行操作。
关于Handler请参考《关于Handler技术》和《Looper和Handler》.
关于Android的线程模型请参考《Android线程模型
比如下面的代码就准不正确:
packagecom.ray.test;
importjava.util.Timer;
importjava.util.TimerTask;
importandroid.app.Activity;
importandroid.os.Bundle;
publicclassJavaTimerextendsActivity{
Timertimer=newTimer();
TimerTasktask=newTimerTask(){
publicvoidrun(){
setTitle("hearme?");
}
};
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timer.schedule(task,10000);
}
}

正确的做法应该通过配合基于UI线程的Handler来进行UI的操作。
正确代码如下:
packagecom.ray.test;
importjava.util.Timer;
importjava.util.TimerTask;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
publicclassTestTimerextendsActivity{
Timertimer=newTimer();
Handlerhandler=newHandler(){
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
case1:
setTitle("hearme?");
break;
}
super.handleMessage(msg);
}
};
TimerTasktask=newTimerTask(){
publicvoidrun(){
Messagemessage=newMessage();
message.what=1;
handler.sendMessage(message);
}
};

publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timer.schedule(task,10000);
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics