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)