Schedule AsyncTask to run every minute

2019-06-08 03:03发布

问题:

What is the best practice to schedule an AsyncTask to have it run every minute (note that after the AsyncTask has finished I should be able to update the UI).

I'm not intending on using a Service because these tasks should only run when app is active.

EDIT: What the AsyncTask is just downloading JSON data from a webserver (which I need to update UI). The JSON data is pretty small a couple of kilobytes.

回答1:

You have to use a Timer:

timer.schedule(asyncTask, 0, 50000); //execute in every 50000 ms

You can update your UI in the onPostExecute() overrided method of the AsyncTask class.

http://developer.android.com/reference/java/util/Timer.html http://developer.android.com/reference/android/os/AsyncTask.html



回答2:

I'd use a Timer object.

There's a full example:

public class TimerActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyTimerTask myTask = new MyTimerTask();
    Timer myTimer = new Timer();

    myTimer.schedule(myTask, 3000, 1500);
  }

  // In this class you'd define an instance of your `AsyncTask` 
  class MyTimerTask extends TimerTask {
    MyAsyncTask atask;

    final class MyAsyncTask extends AsyncTask<Param1, Param2, Param3> {
      // Define here your onPreExecute(), doInBackground(), onPostExecute() methods
      // and whetever you need
      ...
    }

    public void run() {
      atask = new MyAsyncTask<Param1, Param2, Param3>();
      atask.execute();
    }
  } 
}