I want make an app that call a function for example every 10 sec.
I wrote my code like this:
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
@Override
public void run() {
//call function
}
}, 10000);
But my function call just one time in 10 sec after compile this code.
How can I fix it?
There are number of alternative ways to do this. Personally, I prefer to use ScheduledExecutorService:
You can use Rx java & Rx Android by adding this dependency as below :
checkout Here for the latest version.
You need an Observable like this :
just change
ETA_UPDATE_INTERVALS
to your specific value.You need a Disposable for subscribing to observable and to dispose it when required (Like onCleared() on ViewModels)
You need a Consumer that your repeated logic would go there.
Now you can subscribe(Start repeating function) and dispose(stop) observable every time you need.
Use below code.
Do it like this:
Use a combination of
Timer
andTimerTask
like this:Also make sure to use
runOnUiThread()
if you want to modify the UI.It looks that Timer and TimerTask are what are you looking for