How to run a thread repeatedly after some interval

匆匆过客 提交于 2019-11-26 23:11:25

问题


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

Do i need to use Handler for implementing this?


回答1:


Option 1:

volatile boolean flag = true;

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

        }

    }
}

Option 2:

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

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

}, 0, interval);

Option 3:

volatile boolean flag = true;

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

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

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

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.




回答2:


Prefered choice is

java.util.concurrent.ScheduledExecutorService

Newer and robust implementation, More here ScheduledExecutorService




回答3:


I would use a Timer to achieve this. Try this:

void onCreate()
{
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // Download your stuff
        }

    }, 0, 1000);
}

It starts immediately and the run-Method gets called every second.



来源:https://stackoverflow.com/questions/15406240/how-to-run-a-thread-repeatedly-after-some-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!