我在哪里可以创建和使用的ScheduledThreadPoolExecutor,TimerTask的,或处理程序? [英] Where do I create and use ScheduledThreadPoolExecutor, TimerTask, or Handler?

查看:236
本文介绍了我在哪里可以创建和使用的ScheduledThreadPoolExecutor,TimerTask的,或处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让我的RSS阅读器检查饲料,每10分钟为新帖,然后分析它们是否有新的问题。我还需要更新大约每分钟用户界面。

I need to make my RSS Feed reader check the feed every 10 minutes for new posts, and then parse them if there are new ones. I also need to update the UI about every minute.

我已经阅读并听到不同的东西从各种来源。我现在的理解是,我可以使用的ScheduledThreadPoolExecutor 进行两次调度的线程,其中一人需要一个处理程序更新用户界面。我不能确定什么是最有效的使用这些类或的TimerTask

I have read and heard different things from various sources. My current understanding is that I can use ScheduledThreadPoolExecutor to make two scheduled threads, and one of them needs a Handler for updating the UI. I am unsure about what the most efficient use of these classes or TimerTask.

我也非常不确定的地方,使这些子类。一位朋友建议延长的TimerTask 在我的 FeedParser 类的内部类,使其更简单。但是,要以这种方式实现它,我必须使用运行()方法的TimerTask 没有覆盖它,这意味着我不能简单地用我需要为需要运行函数中的参数。

I am also very uncertain about where to make subclasses of these. One friend suggested extending TimerTask as an inner class in my FeedParser class to make it simpler. However, to implement it in that way, I have to use the run() method for TimerTask without overriding it, meaning I can't simply use the parameters I need for the functions that need to run.

总之,什么是安排这个任务的最佳途径,我会在哪里实现这些?

In short, what is the best way to schedule the tasks for this, and where would I implement these?

推荐答案

我preFER使用的ScheduledThreadPoolExecutor。一般情况下,如果我正确地理解您的需求,所有这些都可以在您的活动执行,TimerTask的和处理程序不需要,请参见下面示例code:

I prefer to use ScheduledThreadPoolExecutor. Generally, if I understand your requirements correctly, all these can be implemented in your activity, TimerTask and Handler are not needed, see sample code below:

public class MyActivity extends Activity {
  private ScheduledExecutorService scheduleTaskExecutor;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    scheduleTaskExecutor= Executors.newScheduledThreadPool(5);

    // This schedule a task to run every 10 minutes:
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {
        // Parsing RSS feed:
        myFeedParser.doSomething();

        // If you need update UI, simply do this:
        runOnUiThread(new Runnable() {
          public void run() {
            // update your UI component here.
            myTextView.setText("refreshed");
          }
        });
      }
    }, 0, 10, TimeUnit.MINUTES);
  } // end of onCreate()
}

记住要完成/正常关闭运行的任务在Activity.onDestroy(),希望帮助。

Remember to finish/close your runnable task properly in Activity.onDestroy(), hope that help.

这篇关于我在哪里可以创建和使用的ScheduledThreadPoolExecutor,TimerTask的,或处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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