Android 定时器任务或处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20330355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:41:41  来源:igfitidea点击:

Timertask or Handler

androidperformancetimerhandlertimertask

提问by keysersoze

Let's say that I want to perform some action every 10 seconds and it doesn't necessarily need to update the view.

假设我想每 10 秒执行一次操作,并且不一定需要更新视图。

The question is: is it better (I mean more efficient and effective) to use timer with timertask like here:

问题是:将计时器与 timertask 一起使用是否更好(我的意思是更高效),如下所示:

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);
}

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).

此外,如果您能解释何时使用哪种方法以及为什么其中一种方法比另一种方法更有效(如果确实如此),我将不胜感激。

回答by Suragch

Handleris better than TimerTask.

Handler比 好TimerTask

The Java TimerTaskand the Android Handlerboth allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handlerover TimerTaskin Android (see here, here, here, here, here, and here).

JavaTimerTask和 AndroidHandler都允许您在后台线程上安排延迟和重复的任务。但是,绝大多数文献都建议在 Android 中使用Handlerover TimerTask(请参阅此处此处此处此处此处此处)。

Some of reported problems with TimerTask include:

TimerTask 的一些报告问题包括:

  • Can't update the UI thread
  • Memory leaks
  • Unreliable (doesn't always work)
  • Long running tasks can interfere with the next scheduled event
  • 无法更新 UI 线程
  • 内存泄漏
  • 不可靠(并不总是有效)
  • 长时间运行的任务可能会干扰下一个计划事件

Example

例子

The best source for all kinds of Android examples that I have seen is at Codepath. Here is a Handlerexample from there for a repeating task.

我见过的各种 Android 示例的最佳来源是Codepath。这是Handler重复任务的示例。

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      // Do something here on the main thread
      Log.d("Handlers", "Called on main thread");
      // Repeat this the same runnable code block again another 2 seconds
      handler.postDelayed(runnableCode, 2000);
    }
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

Related

有关的

回答by Praveena

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

使用 Timer 有一些缺点

它只创建一个线程来执行任务,如果一个任务运行时间太长,其他任务就会受到影响。它不处理任务抛出的异常,线程只是终止,这会影响其他计划任务并且它们永远不会运行

Copied from:

复制自:

TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

TimerTask vs Thread.sleep vs Handler postDelayed - 每 N 毫秒调用一次函数最准确?

回答by sma6871

Kotlin version of accepted answer:

接受答案的 Kotlin 版本:

val handler = Handler()

val runnableCode = object : Runnable {
    override fun run() {
       Log.d("Handlers", "Called on main thread")
       handler.postDelayed(this, 2000)
    }
}

handler.post(runnableCode)