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.
Asked
Active
Viewed 7.3k times
3 Answers
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
-
What is the 1 in schedule? – Praneeth Feb 09 '16 at 06:10
-
The 1 in schedule is the amount of time in milliseconds before the first execution of the scheduled TimerTask. The 5000 is the amount of delay in between subsequent executions in milliseconds. – Cogentleman May 05 '16 at 23:54
-
1Please mind that this invokes the Runnable on whatever thread this class was created on. – mkrasowski Oct 30 '18 at 11:18
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
-
1The 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