Principle:
Its basic processing model is a single-threaded scheduling task queue model, the timer constantly accept scheduling tasks, all tasks accept timer scheduling after adding Taskqueue,timerthread constantly go to taskqueue task to execute.
It is not difficult to see from the diagram, this is a producer-consumer model of a special case: Multi-producer, single-consumer model.
This type of Message Queuing implementation also has a similar implementation in the programming model in the browser, and the timed execution function settimeout (expression,milliseconds) in JavaScript is also implemented based on this principle.
The disadvantage of this approach is that when a task executes for a long time, it exceeds the time that the next task in Taskqueue starts executing, and it affects the real-time performance of the entire task. In order to improve the real-time, we can use multiple consumers to spend together to improve the processing efficiency and avoid the realization of such problems.
See http://www.cnblogs.com/jinspire/archive/2012/02/10/2345256.html for specific explanations.
Visible TimerTask can be seen as just an event, while a timer is a queue
1.Timer
- Java.util.Timer Timer = new Java.util.Timer (true);
- True indicates that the timer runs in daemon mode (Low priority,
- Program End timer also end automatically), note that javax.swing
- There is also a timer class in the package, if you use the Swing package in import,
- Pay attention to the clash of names.
- TimerTask task = new TimerTask () {
- Public void Run () {
- ... //each time the code needs to be executed is placed in this area.
- }
- };
- Here are a few ways to schedule a task:
- Timer.schedule (task, time);
- Time is a date type: Executed once at the specified times.
- Timer.schedule (Task, firsttime, period);
- Firsttime is a date type and period is a long
- This is done every period milliseconds from the firsttime moment.
- Timer.schedule (task, delay)
- Delay is a long type: it is executed once from now through delay milliseconds
- Timer.schedule (task, delay, period)
- Delay is long,period to long: From now on delay milliseconds, every period
- Milliseconds to execute once.
- Timer.cancel ()//cancels the current timer and all the tasks in that queue (the running task is not affected), no more tasks are added to the queue, and then the timer does nothing
- Timer.purge ()//Remove the canceled task from the queue so that they can be recycled as garbage
2.TimerTask functions of some common functions
Timertask.cancel ()//cancels the current task and moves it out of the queue
The working principle of Android--timer and timertask and the specific meanings of its related functions