40

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;

@Override
protected void onCreate(Bundle bundle)
{
  ...
  m_handler = new Handler();
}

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

public void startRepeatingTask()
{
    m_statusChecker.run(); 
}

public void stopRepeatingTask()
{
    m_handler.removeCallbacks(m_statusChecker);
}  
user2391890
  • 639
  • 1
  • 8
  • 15
  • Try this http://stackoverflow.com/a/14377875/28557 and http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/ – Vinayak Bevinakatti Aug 21 '13 at 09:29
  • I think its easy to use CountDownTimer. See here for tutorial http://androidsolution4u.blogspot.in/2012/12/android-count-down-timer.html – Ketan Ahir Aug 21 '13 at 09:30

5 Answers5

94

Set repeated task using this:

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

    @Override
    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)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

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.

Junyue Cao
  • 421
  • 6
  • 13
Gru
  • 2,686
  • 21
  • 29
  • After the first iteration, I'm getting "Called from wrong thread exception" – fix Nov 23 '15 at 18:43
  • 1
    For Android a Handler is preferable to a Timer: https://stackoverflow.com/questions/20330355/timertask-or-handler – Suragch Jun 12 '17 at 11:44
7

Use a Handler in the onCreate() method. Its postDelayed() method causes the Runnable to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 milliseconds in this example).

Refer this code :

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    android.os.Handler customHandler = new android.os.Handler();
    customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable()
{
    public void run()
    {
        //write here whaterver you want to repeat
        customHandler.postDelayed(this, 1000);
    }
};
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Gazal Patel
  • 480
  • 5
  • 10
  • Suppose my scheduled time is every 10 minutes and my phone goes to Doze mode or the ideal mode or I lock the device. Will the handler still call my method after 10 minutes? Currently, it is not working. Handler only getting called when my Application Resumes. – Aman Verma Sep 11 '18 at 23:02
  • @Sniper you would need to use Alarm Manager for the function to be called when the app isn't running https://developer.android.com/reference/android/app/AlarmManager.html – Ebrahim Karam Apr 28 '19 at 04:39
5

use TimerTask to call after specific time interval

    Timer timer = new Timer();
    timer.schedule(new UpdateTimeTask(),1, TimeInterval);

and

  class UpdateTimeTask extends TimerTask {

        public void run() 
           {        
            // do stufff
           }

        }
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
2

Do it in Android's way with the help of Handler.

Declare a Handler which does not leak Memory

/**
     * Instances of static inner classes do not hold an implicit
     * reference to their outer class.
     */
    private static class NonLeakyHandler extends Handler {
        private final WeakReference<FlashActivity> mActivity;

        public NonLeakyHandler(FlashActivity activity) {
            mActivity = new WeakReference<FlashActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            FlashActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }

Declare a runnable which handle your task

   private Runnable repeatativeTaskRunnable = new Runnable() {
        public void run() {
            new Handler(getMainLooper()).post(new Runnable() {
                @Override
                public void run() {

         //DO YOUR THINGS
        }
    };

Initialize handler object in your Activity/Fragment

//Task Handler
private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);

Repeat task after fix time interval

taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);

Stop repetition

taskHandler .removeCallbacks(repeatativeTaskRunnable );

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
  • Suppose my scheduled time is every 10 minutes and my phone goes to Doze mode or the ideal mode or I lock the device. Will the handler still call my method after 10 minutes? Currently, it is not working. Handler only getting called when my Application Resumes – Aman Verma Sep 11 '18 at 23:03
0

You have to put this code inside the activity you want to call every 5 seconds

final Runnable tarea = new Runnable() {   public void run() {
hola_mundo();//the operation that you want to perform }}; 
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(tarea, 5, 5, TimeUnit.SECONDS);