定时器任务或处理程序

编程入门 行业动态 更新时间:2024-10-10 23:25:14
本文介绍了定时器任务或处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

问题是:像这样使用 timer 和 timertask 是否更好(我的意思是更高效):

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

或者只是一个带有延迟的处理程序

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

推荐答案

Handler 优于 TimerTask.

Handler is better than TimerTask.

Java TimerTask 和 Android Handler 都允许您在后台线程上安排延迟和重复的任务.然而,文献中绝大多数建议在 Android 中使用 Handler 而不是 TimerTask(参见 此处,此处a>,这里,此处,此处 和 此处).

The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).

一些已报告的 TimerTask 问题包括:

Some of reported problems with TimerTask include:

  • 无法更新 UI 线程
  • 内存泄漏
  • 不可靠(并不总是有效)
  • 长时间运行的任务可能会干扰下一个预定的事件

示例

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

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

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

相关

  • Handler vs Timer:固定周期执行和固定速率执行安卓开发

更多推荐

定时器任务或处理程序

本文发布于:2023-11-27 13:18:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定时器   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!