how can I call function every 10 sec?
Asked Answered
C

6

18

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?

Coetaneous answered 4/2, 2014 at 13:27 Comment(2)
user timer and schedual themWhiteside
add ha.postDelayed(this, 10000); at the end of runVeal
D
25

Do it like this:

final Handler ha=new Handler();
ha.postDelayed(new Runnable() {

    @Override
    public void run() {
        //call function

        ha.postDelayed(this, 10000);
    }
}, 10000);
Dandridge answered 4/2, 2014 at 13:37 Comment(2)
your way take very much ram & can be slow deviceCoetaneous
how can we implement same thing with the Timer ?Significance
O
9

Use a combination of Timer and TimerTask like this:

int delay = 0; // delay for 0 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
{ 
    public void run() 
    { 
        //Call function
    } 
}, delay, period); 

Also make sure to use runOnUiThread() if you want to modify the UI.

Overawe answered 4/2, 2014 at 13:29 Comment(3)
I do it.but my app call function one time & then my app hang & force close. how can I fix it?Coetaneous
Hard to tell without your LogCat.Overawe
You might be modifying the UI and not using runOnUiThread() as mentioned earlier by FD_Ding
F
6

You can use Rx java & Rx Android by adding this dependency as below :

//Rx Java
implementation 'io.reactivex.rxjava2:rxjava:2.2.13'

//Rx Android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

checkout Here for the latest version.

You need an Observable like this :

private final Observable etaUpdateRepeatableObservable =
        Observable
                .interval(ETA_UPDATE_INTERVALS, TimeUnit.MINUTES)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .repeat();

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)

private Disposable etaUpdateDisposable;

You need a Consumer that your repeated logic would go there.

private final Consumer etaUpdateConsumer = o -> {
    //Here you got the repeated logic
};

Now you can subscribe(Start repeating function) and dispose(stop) observable every time you need.

  private void addEtaUpdateDisposable() {
    if (etaUpdateDisposable == null) {
        etaUpdateDisposable = etaUpdateRepeatableObservable.subscribe(etaUpdateConsumer);
    }
}

private void disposeEtaUpdate() {
    if (
            etaUpdateDisposable != null &&
                    !etaUpdateDisposable.isDisposed()
    ) {
        etaUpdateDisposable.dispose();
        etaUpdateDisposable = null;
    }
}
Flyaway answered 14/11, 2019 at 16:29 Comment(0)
B
3

It looks that Timer and TimerTask are what are you looking for

Timer timer = new Timer();

TimerTask timerTask = new TimerTask() {       
    @Override
     public void run() {
         //your code
     });
}
    };

timer.schedule(timerTask, 0, 10000);
Bipod answered 4/2, 2014 at 13:44 Comment(4)
I do it.but my app call function one time & then my app hang & force close. how can I fix it?Coetaneous
you have to give us more details. it is hard to know why your app is hanging without code...Bipod
i am using timer Task and also handler but handler and timer task continue going so after 10 to 15 minuet whole app and phone is hang and freeze is there any solution for that ?Piano
Create Handler object before TimerTask and then use that handler object inside run() method. handler.post(new Runnable() { public void run(){ Update UI } );Bipod
B
0

Use below code.

Timer myTimer = new Timer();
            myTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //your function
                }
            }, 10000);
Befitting answered 4/2, 2014 at 13:30 Comment(2)
I do it.but my app call function one time & then my app hang & force close. how can I fix it?Coetaneous
Create Handler object and then use it inside run() method to update UI.Bipod
B
0

There are number of alternative ways to do this. Personally, I prefer to use ScheduledExecutorService:

Bandage answered 4/2, 2014 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.