0

My requirement is to call an async task repeatedly every 10 seconds so that the webservice will fetch data an do the update (updating of a map and image) accordingly.

I searched throughout and found out that one can use a tasktimer for this. The problem I am facing is that a parameter is passed into my asynctask. But I am not able to pass that parameter into the tasktimer.

I found out that for this a separate class should be created which extends timer task. But I have no idea how to get that done according to my need.

Please be kind enough to help me. The code for passing a parameter to the async task is given below.

new AsyncLoadGpsDetails().execute(userName);

I want to repeatedly perform the async task. PLease help me, I don't know how to create the class which extends tasktimer as I'm a newbie to this.

Thanks & Regards in advance

Luke Willis
  • 8,429
  • 4
  • 46
  • 79
Randi_789
  • 37
  • 2
  • 12
  • 1
    If you want to do something every X seconds repeatedly its probably more correct to use a Thread than an AsyncTask. A Thread can just loop forever with a sleep at the end to wait for the next iteration, rather than constantly creating AsyncTasks (which can cause delays if you need to create a different AsyncTask ever). – Gabe Sechan Aug 18 '14 at 15:31
  • From what I understand, you would be better off actually using a `Service`. You can then set up broadcast receivers to communicate between your main activity and the service to send any parameters to it. – Aleks G Aug 18 '14 at 15:39
  • But my requirement is to do it with async task ,, can you help me out – Randi_789 Aug 18 '14 at 15:39

2 Answers2

0

Here is an example of a Timer and TimerTask:

private Timer mTimer;
private TimerTask mTimerTask;

private void launchTimerTask() {

    mTimer = new Timer();
    mTimerTask = new TimerTask() {
        @Override
        public void run() {
            // Perform your recurring method calls in here.
            new AsyncLoadGpsDetails().execute(userName);
        }
    };
    mTimer.schedule(mTimerTask, // Task to be executed multiple times
            0, // How long to delay in Milliseconds
            10000); // How long between iterations in Milliseconds
}

private void finishTimerTask() {
    if (mTimerTask != null) {
        mTimerTask.cancel();
    }
    if (mTimer != null) {
        mTimer.purge();
        mTimer.cancel();
    }
}

For the TimerTask you will need the following imports:

import java.util.Timer;
import java.util.TimerTask;

If possible, I would use a ScheduledExecutor (Java Timer vs ExecutorService?). There are many examples around, but here is a quick snippet:

private ScheduledExecutorService mService;
private ScheduledFuture mFuture;

private void launchScheduledExecutor() {
    mService = Executors.newSingleThreadScheduledExecutor();
    mFuture = mService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // Perform your recurring method calls in here.
                new AsyncLoadGpsDetails().execute(userName);
            }
        },
        0, // How long to delay the start
        10, // How long between executions
        TimeUnit.SECONDS); // The time unit used
}

private void finishScheduledExecutor() {
    if (mFuture != null) {
        mFuture.cancel(true);
    }
    if (mService != null) {
        mService.shutdown();
    }
}

Be sure to shutdown the ExecutorService when you're done.

For the above snippet you'll need the following imports:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

You can call launch anywhere (an onClickListener or onCreate perhaps). Just be sure to call 'finish' at some point or they will run indefinitely (in the onDestroy for example)

Community
  • 1
  • 1
Taylor Frey
  • 374
  • 4
  • 6
  • Nope, sure don't. Just be sure to add the imports I listed. – Taylor Frey Aug 18 '14 at 15:51
  • Sir i tried it out, but it says "ScheduleExecutorService cannot be resolved to a type" – Randi_789 Aug 18 '14 at 15:55
  • Sounds like you're using Eclipse. If you've got the proper import statements and such, then I believe simply restarting Eclipse tends to clear that error. Sometimes a clean and build may be required as well. – Taylor Frey Aug 18 '14 at 16:14
  • Sir is it ScheduleExecutorService or ScheduledExecutorService – Randi_789 Aug 18 '14 at 16:23
  • Scheduled with a 'd' for both the Executor and the Future. Edited answer to reflect the changes. – Taylor Frey Aug 18 '14 at 16:24
  • Sir, i tried it out, but i my map doesn't seem to update. Sir where do i have to perform this method. In oncreate or onpost execute – Randi_789 Aug 18 '14 at 16:46
  • Edited answer with a bit more detail. I would put the creation and start in the `onCreate()` method of the Activity or Fragment and the `service.shutdown()` in `onDestroy()`. – Taylor Frey Aug 18 '14 at 18:06
  • Sit, Thank You very much for your answer ,,, there's a small issue sir, this method doesn't run the doin backgorund method repeatedly... Do you have any idea on how to get that workin ??,,,,,,By the way thankyou very much sir for tolerating all this and lending me your fullest support – Randi_789 Aug 18 '14 at 19:05
  • Sorry, my fault... Looking at the documentation, a single instance of the AsyncTask is only executed once "The task can be executed only once (an exception will be thrown if a second execution is attempted.)" [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html). Create a new `AsyncLoadGpsDetails()` in the `run()` method. – Taylor Frey Aug 18 '14 at 20:29
  • Sir, still the Async task doesn't seem to return values from the webservvice ?? – Randi_789 Aug 19 '14 at 06:31
0

You can use either use scheduleAtFixedRate or scheduleWithFixedDelay...

scheduleAtFixedRate

  // this task for specified time it will run Repeat
  repeatTask.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
              // Here do something
              // This task will run every 10 sec repeat
        }
  }, 0, 10);

scheduleWithFixeDelay

scheduler.scheduleWithFixedDelay(new TimerTask() {
  @Override
  public void run() {
              // Here do something
              // This task will run every 10 sec Delay
        }
  },, 0, 10, TimeUnit.SECONDS);

Find the difference between them Here

Community
  • 1
  • 1
Nadeem Iqbal
  • 2,357
  • 1
  • 28
  • 43
  • Sir do i have run this method inside oncreate or inside the async task ? – Randi_789 Aug 18 '14 at 16:01
  • I think, you don't need to run any async task now, just paste your code in run(){...} method... But you can run async task also – Nadeem Iqbal Aug 18 '14 at 16:04
  • Sir, but my webservice will be called and handled in the async task,, so do i have to copy and paste the async task inside this sir,,!!! and also sir is repeatTask a timer type variable ??? – Randi_789 Aug 18 '14 at 16:08
  • Ok, Use async task in run method, and It will be called again and again, until you shut it down... I think you should use scheduleWithFixedDelay() because your async requests to the network and there may be a delay in response – Nadeem Iqbal Aug 18 '14 at 16:11
  • Sir , i tried it , but it gives an erroneous syntax,, sorry for bothering you like this sir – Randi_789 Aug 18 '14 at 16:16