如何在一定的时间间隔后重复运行一个线程 [英] How to run a thread repeatedly after some interval

查看:151
本文介绍了如何在一定的时间间隔后重复运行一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要运行一个线程(它一些时间在后台耗时的任务,不更新UI),它只是下载了一些文件,形成了互联网,它是独立于用户界面。

I want to run a thread (Which does some time consuming task in background and does NOT update UI) it just downloads some files form the internet and it is independent from the UI.

我想一段时间间隔后重复运行这个线程。

I want to run this thread repeatedly after some time interval.

我怎样才能做到这一点,我有螺纹类似如下:

How can i do this, I have thread something like below:

boolean mResult =false;

void onCreate()
{
    DownloadThread mDownloadThread = new DownloadThread();
    mDownloadThread.start();
}

class DownloadThread extends Thread implements Runnable
{
    public void run() 
    {
       // My download code 
       mResult  = result;
    }
}

我是否需要使用处理程序实施呢?

推荐答案

选项1:

volatile boolean flag = true;

public void run() 
{
    while(flag)
    {    
       // Do your task
        try{
            Thread.Sleep(interval);
        } catch(Exception e){

        }

    }
}

选项2:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        // Do your task
    }

}, 0, interval);

选项3:

volatile boolean flag = true;

public void someMethod(){
     // Do your task
     try{
         Thread.Sleep(interval);
     } catch(Exception e){

     }
     if(flag)
        return;
     else
        someMethod();     
}

方法4:

final Handler handler = new Handler();
volatile boolean flag = true;

Class A implements Runnable{
    public void run(){
        // Do your Task
    }
    if(!flag)
       handler.postDelayed(a, interval);
}

A a = new A();

handler.postDelayed(a);

将有更多的选择。我从来没有尝试过的选项3和4,刚来到我的脑海里,我写道。如果我是你,我会使用任何1或2。

There will be many more options. I never tried option 3 and 4. It just came to my mind and I wrote. If I were you I would use any of 1 or 2.

这篇关于如何在一定的时间间隔后重复运行一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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