0

I want to run Async Task in Android every intervals.

my interval is = { 15 min , 30 min , 1 hour ....etc

Depending on the users' choice.

When I start my application then I want to fetch my current time and after every n interval I want to execute Async Task

   int intv = 15;
   SimpleDateFormat sd = new SimpleDateFormat(
            "HH:mm:ss");
    Date date = new Date();
    sd.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
    System.out.println(sd.format(date));
    String currenttime = sd.format(date);
    Date myDateTime = null;
    try
      {
        myDateTime = sd.parse(currenttime);
      }
    catch (ParseException e)
      {
         e.printStackTrace();
      }
    System.out.println("This is the Actual        Date:"+sd.format(myDateTime));
    Calendar cal = new GregorianCalendar();
    cal.setTime(myDateTime);

            cal.add(Calendar.MINUTE , intv ); //here I am adding Interval
    System.out.println("This is Hours Added Date:"+sd.format(cal.getTime()));
    try {
        Date afterintv = sd.parse(sd.format(cal.getTime()));
        if(afterintv.after(myDateTime)){  //here i am comparing 
            System.out.println("true..........");
            new SendingTask().execute;  //this is the function i have to execute
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

But I am not getting how to do.

Skand kumar
  • 93
  • 1
  • 1
  • 9

1 Answers1

0

If you want to run the AsyncTask after sometime you can use Thread.sleep in your AsyncTask. In this case is the SendingTask class. Here is a sample:

class SendingTask extends AsyncTask{

    // Interval is in milliseconds
    int interval = 1000;

    public SendingTask(int interval) {
        // Setting delay before anything is executed
        this.interval = interval;
    }

    @Override
    protected Object doInBackground(Object[] params) {
        // Wait according to interval
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        // update UI and restart asynctask
        textView3.setText("true..........");
        new SendingTask(3000).execute();
    }
}
  • **Yes Its working actually ..because I have to take input as interval from user and after every same interval i have tosend data to server ** but i didnt get why you are using 1000 first time and 3000 next time , my interval is 15 minutes means 15*60*1000 so I have to use same interval – Skand kumar Mar 27 '16 at 10:21