Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Particular Method after regular interval of time

In my android application I want to call particular method at regular interval of time ie. "after every 5 seconds"...how can i do that....?

like image 817
Nirav Avatar asked Jan 06 '11 06:01

Nirav


People also ask

Which function used to call function repeatedly after specific time interval?

The setInterval() method repeats a given function at every given time-interval. window.setInterval(function, milliseconds);

How do you call a function repeatedly after a fixed time interval in Java?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.


2 Answers

You can use Timer for the fixed-period execution of a method.

Here is a sample of code:

final long period = 0;
new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        // do your task here
    }
}, 0, period);
like image 79
Vikas Patidar Avatar answered Nov 17 '22 15:11

Vikas Patidar


This link above is tested and works fine. This is the code to call some method every second. You can change 1000 (= 1 second) to any time you want (e.g. 3 seconds = 3000)

public class myActivity extends Activity {

private Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {          
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

private void TimerMethod()
{
    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
}


private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI.               

    //Do something to the UI thread here

    }
};
}
like image 40
herokey Avatar answered Nov 17 '22 13:11

herokey