一:如何使用
自定义一继承于TimerTask
的类,并重写其run()
方法即可。也可以采取匿名类的形式,直接重写其run()
方法。
二:方法
TimeTask有一抽象方法run()
,其作用就是用来放我们处理的逻辑任务。
Timer有一schedule()
方法,重载参数和另外两个方法如下表:
重载方法/常用方法 | 作用 |
---|---|
schedule(TimerTask task, Date time) | 执行task 一次,执行时间为time |
schedule(TimerTask task, Date firstTime, long period) | 执行task ,时间为firstTime , 每次执行间隔为period ,单位毫秒 |
schedule(TimerTask task,long delay) | 执行task 一次,延迟执行时间为delay ,单位毫秒 |
schedule(TimerTask task,long delay,long period) | 执行task ,延迟执行时间为delay ,每次执行间隔为period ,单位毫秒 |
cancal() | 终止此计时器,丢弃所有当前已安排的任务 |
purge() | 从此计时器的任务队列中移除所有已取消的任务 |
三:例子
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import java.util.Timer; import java.util.TimerTask; class Delay extends TimerTask{ int times; @Override public void run() { // TODO Auto-generated method stub times++; System.out.println("Delay Task is delaying to do. " + times); // If launch times big than 10, then cancel the TimeTask. if(times >= 10){ this.cancel(); } } } public class DelayTask { public static void main(String args[]){ Timer timer = new Timer(); timer.schedule(new Delay(), 0, 1000); } }
或者
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import java.util.Timer; import java.util.TimerTask; public class DelayTask { public static void main(String args[]){ TimerTask timerTask2 = new TimerTask(){ public void run(){ System.out.println("Unknown Task is delaying to do."); } }; Timer timer2 = new Timer(); timer2.schedule(timerTask2, 1000); } }
四:知识补充
读者看到“重写run()
”方法时或许已经猜到Timer与Thread是否有某种关系。事实上Timer内部利用了一个后台线程 TimerThread 有计划地执行指定任务。一个 Timer 对象对应的是单个后台线程,其内部维护了一个 TaskQueue,用于顺序执行计时器任务 TimeTask。
最后
以上就是欣喜紫菜最近收集整理的关于定时器(Timer)的讲解的全部内容,更多相关定时器(Timer)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复