The following content is translated according to the JAVATM Tutorial and related API doc for future reference:1. 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.
A simple routine:
mport Java.util.timer;import java.util.TimerTask;/** * Simple demo this uses Java.util.Timer to schedule a task to execute* once 5 seconds has passed.*/ Public classReminder {Timer timer; PublicReminder (intseconds) {Timer=NewTimer (); Timer.schedule (NewRemindtask (), seconds* +); } classRemindtask extends TimerTask { Public voidrun () {System. out. println ("Time ' s up!"); Timer.cancel (); //Terminate the timer thread } } Public Static voidMain (String args[]) {System. out. println ("About to Schedule task."); NewReminder (5); System. out. println ("Task scheduled."); }}
To run this small example, you will first see:
About to schedule task.
After 5 seconds you will see:
Time ' s up!
This small example illustrates some of the basic steps to implement and plan a task with a timer thread:
- To implement a subclass of a custom TimerTask, the Run method contains the task code to execute, in this case the subclass is Remindtask.
- Instantiate the Timer class and create a timers background thread.
- Instantiates a Task object (
new RemindTask()
).
- Develop an execution plan. Here, with the schedule method, the first parameter is the TimerTask object, and the second parameter indicates the delay time before execution starts (in milliseconds, 5000 is defined here). There is also a way to specify the execution time of a task, as the following example specifies that the task is performed at 11:01 p.m.:
// Get the Date corresponding to 11:01:00 pm today. Calendar calendar = calendar.getinstance (); calendar. Set at ); calendar. Set 1 ); calendar. Set 0 =new Timer (); Timer.schedule (new remindtask (), time);
2. Terminating the timer thread
By default, the program stays running as long as a program's timer thread is running. Of course, you can terminate a timer thread in the following four ways:
- Call the timer's Cancle method. You can call this method from anywhere in the program, even in a timer task's Run method.
- Make the timer thread a daemon thread (you can use the new timer (true) to reach this point when you create the timer), so that when the program has only daemon threads, it will automatically terminate the run.
- When all the tasks related to the timer have been executed, delete all references to this timer object (NULL) so that the timer thread terminates.
- Call the System.exit method to terminate the entire program (all threads).
The reminder example uses the first method. The second method cannot be used here, because it requires the program to remain running until the timer's task is completed, and if it is set to daemon, then when the main thread ends, the program only has the timer daemon thread, The program does not terminate when the timer thread executes the task.
Sometimes, the termination of a program is not only related to the timer thread. For example, if we use AWT to beep, then AWT will automatically create a non-daemon thread to keep the program running. The following code we have modified reminder, added the beeping function, so we need to join the SYSTEM.EXIT call to terminate the program.
import Java.util.timer;import java.util.timertask;import java.awt.Toolkit;/** * Simple demo this uses Java.util.Timer to schedule a task to execute* once 5 seconds has passed.*/ Public classreminderbeep {Toolkit Toolkit; Timer timer; PublicReminderbeep (intseconds) {Toolkit=Toolkit.getdefaulttoolkit (); Timer=NewTimer (); Timer.schedule (NewRemindtask (), seconds* +); } classRemindtask extends TimerTask { Public voidrun () {System. out. println ("Time ' s up!"); Toolkit.beep (); //Timer.cancel ();//Not necessary because we call System.exitSystem.exit (0);//Stops the AWT thread (and everything else) } } Public Static voidMain (String args[]) {System. out. println ("About to Schedule task."); NewReminderbeep (5); System. out. println ("Task scheduled."); }}
3. Perform a task repeatedly
Let's look at an example:
Public classannoyingbeep {Toolkit Toolkit; Timer timer; PublicAnnoyingbeep () {Toolkit=Toolkit.getdefaulttoolkit (); Timer=NewTimer (); Timer.schedule (NewRemindtask (),0,//Initial delay 1* +);//subsequent rate } classRemindtask extends TimerTask {intNumwarningbeeps =3; Public voidrun () {if(Numwarningbeeps >0) {toolkit.beep (); System. out. println ("beep!"); Numwarningbeeps--; } Else{toolkit.beep (); System. out. println ("Time ' s up!"); //Timer.cancel ();//Not necessary because we call System.exitSystem.exit (0);//Stops the AWT thread (and everything else) } } } ...}
execution, you will see the following output:
Task scheduled.
Beep!
Beep! //one Second after the first beep
Beep! //one Second after the second beep
Time ' s up! //one Second after the third beep
Here, the schedule method with three parameters is used to specify that the task executes once every second. As listed below, all timer classes are used to develop a method for planning recurring tasks:
schedule(TimerTask task, long delay, long period)
schedule(TimerTask task, Date time, long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
When planning a recurring task, if you focus on the smoothness of the task execution, then use the schedule method, if you care about the frequency of the execution of the task, then use the Scheduleatfixedrate method. For example, the schedule method is used here, which means that the interval between all beep is at least 1 seconds, that is, if there is a beap that is late for some reason (not executed as planned), then all the remaining beep are deferred. If we want this program to terminate in just 3 seconds, whichever beep is delayed for whatever reason, then we need to use the Scheduleatfixedrate method so that when the first beep is late, Then the beep will be executed at the fastest speed (maximum compression interval).
4. Further analysis of schedule and Scheduleatfixedrate
(1) Schedule of 2 parameters The task is executed immediately when the scheduled execution time of the specified Scheduledexecutiontime<=systemcurrenttime is established. Scheduledexecutiontime does not change because of the excessive execution of a task.
(2) Schedule of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task changes with the actual execution time of the previous one, that is, scheduledexecutiontime (n+1) = Realexecutiontime (nth time) +periodtime. That is, if the nth execution of a task, for some reason the execution time is too long, after the execution of the Systemcurrenttime>=scheduledexecutiontime (n+1), then do not wait for a moment, immediately execute the n+ 1 tasks, and the next n+2 task Scheduledexecutiontime (n+2) becomes realexecutiontime (n+1 times) +periodtime. plainly, this approach is more focused on keeping the interval stable.
(3) The scheduleatfixedrate of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task is initially determined, i.e. scheduledexecutiontime (nth time) = Firstexecutetime+n*periodtime; If the nth execution of a task is for some reason the execution time is too long, after the execution of the Systemcurrenttime>=scheduledexecutiontime (nth + 1 times), then do not do period interval wait, immediately execute the N+1 task, and the next n+2 task of Scheduledexecutiontime (n+2) still firstexecutetime+ (n+2) * Periodtime This is the first time that a task is executed. plainly, this approach is more focused on maintaining the stability of the execution frequency.
5. Some issues of attention
- Each timer only corresponds to a single thread.
- The timer does not guarantee that the task executes very precisely.
- The Timer class is thread-safe.
Android Timer and TimerTask