I. Overview
A timer is a timer tool that is used to schedule a specified task in a background thread. It can schedule a task to execute once or repeatedly.
TimerTask an abstract class whose subclasses represent a task that can be scheduled by the timer.
Second, the Timer and timertask related operation
Timer function is realized by combining timer with TimerTask. The specific implementation process is as follows:
The first step is to get the Timer instantiation object
Timer timer= new timer ();
Step Two, instantiate the TimerTask object
timertask timertask = new TimerTask () {
Publicvoid Run () {
Doing something
}
}
When instantiating a TimerTask object, you need to rewrite its run () method, and then add the specific actions that need to be performed in the body of the method. For example, output a word, send a message and so on.
Step three, start the timer
timer.schedule (timertask, delay, period);
This completes the process of creating and starting a timer, but in practice it may require some other means of operation.
because the parameters of the timer are modified at some point, such as Delay,period, during the course of the program's operation. In order to use the latest and correct data in a timely manner, the existing timer needs to be closed and re-created and started with the new parameters.
The first step is to cancel the timertask and delete it in the timer timer queue.
If(TimerTask = = null) {
TimerTask. Cancel();
}
Second Step, restart the timer
If(timertask! = null) {
TimerTask = new TimerTask(
public void Run() {
Do something
}
) ;
}
Timer.schedule(timetask,delay,period);
It is noteworthy that the Cancle () method is executed after the TimerTask, when restarting the timer, you must re-instantiate the TimerTask is OK, otherwise it will be reported "Java.lang.IllegalStateException: TimerTask is scheduled already"error. Each timer task TimerTask can only be placed once
Android Timer with TimerTask