Nemin Shah
Nemin Shah

Reputation: 301

How to call asyncTasks periodically

I have two AsyncTasks doing network operations. I want to call them periodically (like after one min.). How do I do that? I dont think I can do it on the UI thread. Do i need to create a new thread? Is it possible to implemet this without AlarmManager/Service?

Basically I want to exectue these two statements periodically after one min.

new UploadAsyncTask().execute();
new DownloadAsyncTask().execute();

Thank you

Upvotes: 7

Views: 6033

Answers (1)

Alexis C.
Alexis C.

Reputation: 93902

Just use a timer.

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {       
     @Override
     public void run() {
       handler.post(new Runnable() {
          public void run() {  
             new UploadAsyncTask().execute();
             new DownloadAsyncTask().execute();
          }
        });
      }
};
timer.schedule(task, 0, 1000); //it executes this every 1000ms

Upvotes: 20

Related Questions