24

I'm struggling to find documentation for the TimerTask function on Android. I need to run a thread at intervals using a TimerTask but have no idea how to go about this. Any advice or examples would be greatly appreciated.

Aditya
  • 5,509
  • 4
  • 31
  • 51
Alex Haycock
  • 375
  • 2
  • 3
  • 12

3 Answers3

72

I have implemented something like this and it works fine:

    private Timer mTimer1;
    private TimerTask mTt1;
    private Handler mTimerHandler = new Handler();

    private void stopTimer(){
        if(mTimer1 != null){
            mTimer1.cancel();
            mTimer1.purge();
        }
    }

    private void startTimer(){
        mTimer1 = new Timer();
        mTt1 = new TimerTask() {
            public void run() {
                mTimerHandler.post(new Runnable() {
                    public void run(){
                        //TODO
                    }
                });
            }
        };

        mTimer1.schedule(mTt1, 1, 5000);
    }
Alex
  • 6,957
  • 12
  • 42
  • 48
39

You use a Timer, and that automatically creates a new Thread for you when you schedule a TimerTask using any of the schedule-methods.

Example:

Timer t = new Timer();
t.schedule(myTimerTask, 1000L);

This creates a Timer running myTimerTask in a Thread belonging to that Timer once every second.

Goran Horia Mihail
  • 3,536
  • 2
  • 29
  • 40
Jave
  • 31,598
  • 14
  • 77
  • 90
  • 1
    The above code creates a `Timer` running the task in a thread _only once_ after one second. To run a task once every second, use this overloaded `schedule` method: `schedule(TimerTask task, long delay, long period)`. For example, `timer.schedule(myTimerTask, 1000L, 2000L)` creates a timer that runs every 2 seconds after initial delay of 1 second. Here is the link to the method [link](https://developer.android.com/reference/java/util/Timer.html#schedule(java.util.TimerTask, long, long))[link] – prasad_ Jan 17 '18 at 07:28
  • The link was formatted wrongly in the above comment. Here is the corrected link for the [methods of Timer](https://developer.android.com/reference/java/util/Timer.html) – prasad_ Jan 17 '18 at 07:36
11

This is perfect example for timer task.

Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
    public void run() {
       //perform your action here
    }
};
timerObj.schedule(timerTaskObj, 0, 15000);
SMR
  • 6,628
  • 2
  • 35
  • 56
Kalai Prakash
  • 141
  • 1
  • 8