定时器Timer
来源:互联网 发布:python getoptions 编辑:程序博客网 时间:2024/05/21 19:27
有时候我们需要定时去完成某项任务,或者每隔一段时间去执行某个任务。这时候需要用到Timer类。
Timer定时器是一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。 与每个Timer 对象相对应的是单个后台线程,用于顺序地执行所有计时器任务。计时器任务应该迅速完成。
Timer类的方法很少,使用起来比较方便。最常用的是schedule()方法。这个方法有四种重载形式:
schedule(TimerTask task, Date time) 安排在指定的时间执行指定的任务。
schedule(TimerTask task, long delay) 安排在指定延迟后执行指定的任务。
schedule(TimerTask task, Date firstTime, long period) 安排指定的任务在指定的时间开始进行重复的固定延迟执行。
schedule(TimerTask task, long delay, long period) 安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
TimerTask是什么呢?顾名思义,就是要完成的任务。
TimerTask是一个抽象类,实现了Runnable接口,所以它是一个线程类,使用TimerTask时要实现run()方法,即指定我们要完成的任务。
2.使用schedule()模拟一个定时炸弹
模拟一个定时炸弹,在程序启动10秒后爆炸。使用schedule(TimerTask task, long delay) 方法,delay代表延迟指定时间后执行任务。
public class TimerBomb {public static void main(String[] args) {//模拟一个定时炸弹,10秒后爆炸new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.out.println("爆炸了.......");}}, 10000);//每隔1秒输出一个时间while(true){try {Thread.sleep(1000);System.out.println(new Date().getSeconds());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
运行程序,程序在10秒后爆炸。
3.使用schedule()模拟一个连环定时炸弹
模拟一个定时炸弹,在程序启动5秒后爆炸,然后每隔3秒爆炸一次。使用schedule(TimerTask task, long delay, long period)方法,delay代表延迟指定时间后执行任务,period代表重复执行的任务间隔的时间段。public class TimerBomb {public static void main(String[] args) {//模拟一个定时炸弹,5秒后爆炸,然后每隔3秒爆炸一次new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.out.println("爆炸了.......");}}, 5000, 3000);//每隔1秒输出一个时间while(true){try {System.out.println(new Date().getSeconds());Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
运行程序
public class TimerBomb {//定义一个计数器,用于控制爆炸时间间隔private static int count = 0;public static void main(String[] args) {//模拟一个定时炸弹,分别间隔2秒和4秒爆炸new Timer().schedule(new MyTimerTask(), 2000+2000*count);//每隔1秒输出一个时间while(true){try {System.out.println(new Date().getSeconds());Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//定义一个内部类继承TimerTask,因为每次爆炸后要新创建一个该类对象用于下一次爆炸,//所以不能再使用匿名内部类static class MyTimerTask extends TimerTask {@Overridepublic void run() {System.out.println("爆炸了......");//count用于控制每次不同的爆炸时间间隔count = (count+1)%2;//每个炸弹爆炸完后,都要新建一个炸弹用于下次爆炸new Timer().schedule(new MyTimerTask(), 2000+2000*count);}}}
运行程序
- Timer 定时器
- TIMER 定时器
- timer 定时器
- timer 定时器
- timer定时器
- 定时器 Timer
- 定时器Timer
- timer定时器
- Timer 定时器
- Timer定时器
- 定时器TIMER
- 定时器Timer
- timer定时器
- Timer 定时器
- Timer定时器
- 定时器 timer
- 定时器 Timer
- Timer定时器
- 【算法导论】邻接表存储的拓扑排序
- .hex 文件详解 stm32
- 10大最有效的增加流量方法(必看)
- oracle查找重复记录
- VM 下安装fedora19问题的解决办法
- 定时器Timer
- UIActivityIndicatorView的两种形式 用法一:只显示不停旋转的进度滚轮指示器。
- 真/伪随机数发生器类
- QoS令牌桶工作原理
- Object-c NSString 字符串
- UIManager.cs
- Win32核心编程 读书笔记三 高速缓存行
- struts2输出并下载excel文件
- 第三个项目整理的 前台知识