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.
TimerTask facilitates execution of one-time or recurring tasks using a Timer. TimerTask has really got nothing to do with Threads, apart from the fact that the Timer will execute these tasks in a background thread (though this could be considered an implementation detail of the Timer class).
TimerTask is an abstract class defined in java. util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden.
Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.
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);
}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With