Diego Barrena
Diego Barrena

Reputation: 55

How to execute asynctask every 1 minute?

I have an asynctask that gets the location of a server and makes a marker, the asynctask runs once in OnCreate() and works fine but i need to run it every minute, i read that i need to use timer but i dont understand how to implement it, heres the asynctask:

    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";

    // set json string url 
    String yourJsonStringUrl = url;
    JSONArray dataJsonArr = null;
    @Override
    protected void onPreExecute() {}
    @Override
    protected String doInBackground(String... arg0) {

        try {

            // instantiate json parser
            LatLngActivity jParser = new LatLngActivity();

            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
            // get the array of users
            dataJsonArr = json.getJSONArray(ID_CAMION);
            for (int i = 0; i < dataJsonArr.length(); i++) {

                JSONObject c = dataJsonArr.getJSONObject(i);

                // Storing  JSON item in a Variable
                String JSON_latitude = c.getString(TAG_LATITUDE);
                String JSON_longitude = c.getString(TAG_LONGITUDE);
                //converting JSON variables in double variables
                double HTTP_latitude = Double.parseDouble(JSON_latitude);
                double HTTP_longitude = Double.parseDouble(JSON_longitude);
                HTTP_list.add(HTTP_latitude);
                HTTP_list.add(HTTP_longitude);

                // show the values in logcat
                Log.e(TAG, "latitude: " + HTTP_list.get(0)
                                + ", longitude: " + HTTP_list.get(1)
                );

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
    protected void onPostExecute(String result){
        createHTTPmarker();
    }
}

Upvotes: 3

Views: 6199

Answers (1)

Yash Sampat
Yash Sampat

Reputation: 30611

Use a Timer with a TimerTask. Define the following method in your Activity:

private void setRepeatingAsyncTask() {

    final Handler handler = new Handler();
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {       
                    try {
                        AsyncTaskParseJson jsonTask = new AsyncTaskParseJson();                        
                        jsonTask.execute();
                    } catch (Exception e) {
                        // error, do something
                    }
                }
            });
        }
    };

    timer.schedule(task, 0, 60*1000);  // interval of one minute

}

Now call setRepeatingAsyncTask() from your onCreate() or onResume().

Upvotes: 12

Related Questions