048android初级篇之定时器Timer和TimerTask的详细使用

Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。

TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务,需要重载run()方法,在其中实现自己的功能。

Timer 类API接口

构造函数

1. Timer()
Creates a new timer.
2. Timer(boolean isDaemon)
Creates a new timer whose associated thread may be specified to run as a daemon.
3. Timer(String name)
Creates a new timer whose associated thread has the specified name.
4. Timer(String name, boolean isDaemon)
Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

文中有提到

daemon Thread

daemon Thread可以翻译为守护进程,不过跟linux系统中的守护系统完全是两码事哦。

daemon是相于user线程而言的,可以理解为一种运行在后台的服务线程,比如时钟处理线程、idle线程、垃圾回收线程等都是daemon线程。
daemon线程的主要特点就是"比较次要",程序中如果所有的user线程都结束了,那这个程序本身就结束了,不管daemon是否结束。而user线程就不是这样,只要还有一个user线程存在,程序就不会退出。

name
这个没有发现有什么用。


其他函数

1. void     cancel()
    终止timer,丢弃所有任务的调度
    Terminates this timer, discarding any currently scheduled tasks.
2. int  purge()
    Removes all cancelled tasks from this timer's task queue.
    终止所有被取消的任务。
3. void     schedule(TimerTask task, Date time)
    Schedules the specified task for execution at the specified time.
    在指定的时间,运行此任务。
4. void     schedule(TimerTask task, Date firstTime, long period)
    Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
    在指定的时间Date firstTime运行此任务,之后每间隔long period时间运行一次。
5. void     schedule(TimerTask task, long delay)
    Schedules the specified task for execution after the specified delay.
    
6. void     schedule(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
7. void     scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
    Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
8. void     scheduleAtFixedRate(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

schedule和scheduleAtFixedRate的差异

这两个方法都是任务调度方法,他们之间区别是,schedule会保证任务的间隔是按照定义的period参数严格执行的,如果某一次调度时间比较长,那么后面的时间会顺延,保证调度间隔都是period,而scheduleAtFixedRate是严格按照调度时间来的,如果某次调度时间太长了,那么会通过缩短间隔的方式保证下一次调度在预定时间执行。举个栗子:你每个3秒调度一次,那么正常就是0,3,6,9s这样的时间,如果第二次调度花了2s的时间,如果是schedule,就会变成0,3+2,8,11这样的时间,保证间隔,而scheduleAtFixedRate就会变成0,3+2,6,9,压缩间隔,保证调度时间。

继承自class java.lang.Object的函数

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

TimerTask

A task that can be scheduled for one-time or repeated execution by a Timer.

1. protected    TimerTask()
Creates a new timer task.
2. boolean  cancel()
Cancels this timer task.
3. abstract void    run()
The action to be performed by this timer task.
4. long     scheduledExecutionTime()
Returns the scheduled execution time of the most recent actual execution of this task.
??返回下一次执行的时间  这一点不确认,运行测试代码,也不支持此解释,知道的同学指导下哈

总结

TimerTask

  1. TimerTask 只能被schedule一次,然后被cancel后,就不能再被schedule调用,否则会抛异常。

    java.lang.IllegalStateException: TimerTask is canceled

那么如果需要反复注册任务的话,只好重建TimerTask。

Timer

  1. 每一个Timer仅对应唯一一个线程。
  2. Timer不保证任务执行的十分精确。schedule函数尽量让每一次间隔精准,而scheduleAtFixedRate则是,尽量在算好的时间执行。
  3. Timer类的是线程安全的。

测试代码

/**
 * Created by Frank on 2016/8/23.
 */
public class TestTimerActivity extends Activity {

    private final String TAG ="TestTimerActivity";
    private TextView textviewCounter;
    private EditText editer;
    private Button mButtonStart;
    private Button mButtonStop;

    int mCounter =0;
    int mTime =1000;

    Timer mTimer;
    TimerTask mTimerTask;

    public final  int CODE_REFRESH = 1;

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CODE_REFRESH:
                    textviewCounter.setText(""+mCounter++);
                    break;
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.test_timer);
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if(textviewCounter!=null){
                   Message msg= mHandler.obtainMessage();
                    msg.what = CODE_REFRESH;
                    mHandler.sendMessage(msg);
                }
            }
        };

        mButtonStart =(Button) findViewById(R.id.start);
        mButtonStop =(Button) findViewById(R.id.stop);
        textviewCounter =(TextView) findViewById(R.id.textview_counter);
        editer =(EditText) findViewById(R.id.edit_text);

        mButtonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mTimerTask !=null){
                    mTimerTask.cancel();
                    Log.e(TAG,"time = "+mTimerTask.scheduledExecutionTime());
                }
                
                mTimer.purge();
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if(textviewCounter!=null){
                            Message msg= mHandler.obtainMessage();
                            msg.what = CODE_REFRESH;
                            mHandler.sendMessage(msg);
                        }
                    }
                };
                

                //mTime = Integer.parseInt(editer.getText().toString());
                mTime = 800;
                mTimer.schedule(mTimerTask,mTime,mTime);
                Log.e(TAG,"2time = "+mTimerTask.scheduledExecutionTime());

            }
        });

        mButtonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mTimerTask !=null){
                     mTimerTask.cancel();
                }
                mTimer.purge();
            }
        });
    }
}

参考链接

  1. 032android初级篇之Timer的使用及获取栈顶包名
  2. JDK中的Timer和TimerTask详解
  3. Class Timer
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • Timer 定时器相信都不会陌生,之所以拿它来做源码分析,是发现整个控制流程可以体现很多有意思的东西。 在业务开发...
    石先阅读 6,218评论 2 13
  • 在需要按时间计划执行简单任务的情况下,Timer是最常被使用到的工具类。使用Timer来调度TimerTask的实...
    海纳百川_spark阅读 7,649评论 0 13
  • 网络上关于java定时器的文章真的是错误百出,给我的学习造成了很大的困扰,Timer根本就没有线程安全问题,Tim...
    江江的大猪阅读 1,632评论 0 15
  • 生活是什么颜色?时而像晴空万里欢心雀跃的蓝色;时而像乌云密布惨不忍睹的黑色;时而又像不晴不雨波澜不惊的白...
    潇湘慕雨_21d8阅读 338评论 0 1
  • 你说你是正能量,可是你做了哪些正能量的事 你说你快乐,你说你自由,可是你明明被关在笼子里哭泣 你说你张扬,你说你放...
    甜宋儿阅读 137评论 0 1