user2391890 user2391890 - 9 months ago 45
Java Question

How to repeat a task after a fixed amount of time in android?

I want to repeatedly call a method after every 5-seconds and whenever I wish to to stop the repeated call of the method I may stop or restart the repeated call of the method.

Here is some sample code that whats really I want to implement. Please help me in this respect I would be very thankful to you.

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;

protected void onCreate(Bundle bundle)
m_handler = new Handler();

Runnable m_statusChecker = new Runnable()
public void run() {
updateStatus(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);

public void startRepeatingTask()

public void stopRepeatingTask()

Gru Gru
Answer Source

Set repeated task using this:

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)

//Set how long before to start calling the TimerTask (in milliseconds)
//Set the amount of time between each execution (in milliseconds)

and if you wanted to cancel the task simply call t.cancel() here t is your Timer object

and you can also check comment placed below your answer they have given brief information about that.