TimerTask的或处理程序 [英] Timertask or Handler

查看:114
本文介绍了TimerTask的或处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个快速的问题。比方说,我想执行每10秒的一些行动,并不一定需要更新视图。现在的问题是:是否有更好的(我的意思是更加有效的)使用定时器的TimerTask喜欢这里:

Hi I have a quick question. Let's say that I want to perform some action every 10 seconds and it doesn't necessarily need to update the view. The question is: is it better (I mean more efficient and effective) to use timer with timertask like here:

final Handler handler = new Handler();

TimerTask timertask = new TimerTask() {
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {
               <some task>
            }
        });
    }
};
timer = new Timer();
timer.schedule(timertask, 0, 15000);
}

或只是一个postdelayed处理程序

or just a handler with postdelayed

final Handler handler = new Handler(); 
final Runnable r = new Runnable()
{
    public void run() 
    {
        <some task>
    }
};
handler.postDelayed(r, 15000);

此外,我将不胜感激,如果你能解释一下什么时候使用哪种方法,为什么其中一个比另一个更有效(如果它确实是)。谢谢你。

Also I would be grateful if you could explain when to use which approach and why one of them is more efficient than another (if it actually is). Thank you.

推荐答案

有使用定时器的一些缺点

There are some disadvantages of using Timer

它创建只有单个线程来执行任务,如果一个任务需要很长时间才能运行,其他任务受到影响。 它不处理抛出异常的任务和线程刚刚结束,这会影响其他计划的任务,他们从来没有运行

It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer. It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run

从复制:

<一个href="http://stackoverflow.com/questions/18605403/timertask-vs-thread-sleep-vs-handler-postdelayed-most-accurate-to-call-functio">TimerTask VS视频下载器,处理器postDelayed - ?最准确的调用函数每隔N毫秒

这篇关于TimerTask的或处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆