Java timer Timer

Source: Internet
Author: User
Reprinted: http://blog.csdn.net/siyue_qi/archive/2008/05/22/2469316.aspx
[Java] Detailed description of timer and timertask

The following content is translated Based on the javatm tutorial and related API Doc for future reference:
1. Overview
Timer is a timer tool used to schedule the execution of specified tasks in a background thread. It can plan to execute a task once or repeatedly.
Timertask is an abstract class. Its subclass represents a task that can be scheduled by timer.

A simple routine:

Import Java. util. timer;
Import Java. util. timertask;

/**
* Simple demo that uses Java. util. timer to schedule a task to execute
* Once 5 seconds have passed.
*/

Public   Class Reminder {
Timer timer;

Public Reminder ( Int Seconds) {
Timer= NewTimer ();
Timer. Schedule (NewRemindtask (), seconds*1000);
}

Class Remindtask Extends Timertask {
Public   Void Run () {
System. Out. println ("Time's up!");
Timer. Cancel ();//Terminate the timer thread
}
}

Public   Static   Void Main (string ARGs []) {
System. Out. println ("About to schedule task.");
NewReminder (5);
System. Out. println ("Task scheduled.");
}
}

Run this small example and you will first see:

About to schedule task.

5 seconds later, you will see:

Time's up!

This small example illustrates some basic steps for using the timer thread to implement and plan to execute a task:

Implement a custom timertask subclass. The run method contains the task to be executed.CodeIn this example, this subclass is remindtask.
Instantiate the Timer class and create a timer background thread.
Instantiate a task object (New remindtask ()).
Develop an execution plan. The schedule method is used here. The first parameter is the timertask object, and the second parameter indicates the delay time before execution (unit: milliseconds, 5000 defined here ). Another way is to specify the task execution time, as shown in the following example:
// Obtain the date corresponding to 11:01:00 today.
Calendar calendar = calendar. getinstance ();
Calendar. Set (calendar. hour_of_day, 23 );
Calendar. Set (calendar. Minute, 1 );
Calendar. Set (calendar. Second, 0 );
Date time = calendar. gettime ();

Timer = new timer ();
Timer. Schedule (New remindtask (), time );

2. Terminate the timer thread
By default, only oneProgramThe timer thread is running, so this program will keep running. Of course, you can terminate a timer thread in the following four ways:

Call the timer cancle method. You can call this method from anywhere in the program, even in the run method of a timer task.
Make the timer thread a daemon thread (new timer (true) can be used to achieve this goal when the timer is created), so that when the program only has the daemon thread, it will automatically terminate the operation.
After all the tasks related to the timer are executed, delete the references of all the timer objects (set to null), so that the timer thread will terminate.
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 the program needs to run until the timer task is executed completely. If it is set to daemon, when the main thread ends, the program only has the daemon thread timer, so the program will not terminate when the timer thread executes the task.

In some cases, the termination of a program is not only related to the timer thread. For example, if we use AWT for beep, AWT will automatically create a non-daemon thread to keep the program running. The following code modifies the reminder and adds the beeping function. Therefore, we need to add the system. Exit call to terminate the program.

Import Java. util. timer;
Import Java. util. timertask;
Import Java. AWT. toolkit;

/**
* Simple demo that uses Java. util. timer to schedule a task to execute
* Once 5 seconds have passed.
*/

Public   Class Reminderbeep {
Toolkit toolkit;
Timer timer;

Public Reminderbeep ( Int Seconds) {
Toolkit=Toolkit. getdefatooltoolkit ();
Timer= NewTimer ();
Timer. Schedule (NewRemindtask (), seconds*1000);
}

Class Remindtask Extends Timertask {
Public   Void Run () {
System. Out. println ( " Time's up! " );
Toolkit. Beep ();
// Timer. Cancel (); // Not necessary because we call system. Exit
System. Exit ( 0 ); // Stops the AWT thread (and everything else)
}
}

Public   Static   Void Main (string ARGs []) {
System. Out. println ("About to schedule task.");
NewReminderbeep (5);
System. Out. println ("Task scheduled.");
}
}

3. Execute a task repeatedly

Let's take a look at an example:

Public   Class Annoyingbeep {
Toolkit toolkit;
Timer timer;

Public Annoyingbeep () {
Toolkit = Toolkit. getdefatooltoolkit ();
Timer =   New Timer ();
Timer. Schedule ( New Remindtask (),
0 , // Initial Delay
1 * 1000 ); // Subsequent Rate
}

Class Remindtask Extends Timertask {
Int Numwarningbeeps =   3 ;

Public   Void Run () {
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. Exit
System. Exit ( 0 ); // Stops the AWT thread (and everything else)
}
}
}
...
}

Run the command and 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

The schedule method of the three parameters is used to specify that the task is executed every second. The following table lists all the timer classes used to develop methods for executing tasks repeatedly:
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 you plan to execute a task repeatedly, if you pay attention to the smoothness of the task execution, use the schedule method. If you care about the task execution frequency, use the scheduleatfixedrate method. For example, the schedule method is used here, which means that the interval between all beep is at least one second. That is to say, if a beap is late for some reason (not executed as planned ), all the remaining beep instances must be executed in a delayed manner. If we want to terminate this program after 3 seconds, no matter which beep is delayed for any reason, we need to use the scheduleatfixedrate method so that when the first beep is late, the following beep will be executed closely at the fastest speed (the maximum compression interval ).

4. Further analysis of schedule and scheduleatfixedrate

(1) When schedule with two parameters develops a task plan, if the specified plan execution time scheduledexecutiontime <= systemcurrenttime, the task will be executed immediately. Scheduledexecutiontime will not change because of the excessive execution of a task.
(2) Schedule with three parameters changes the execution time of each plan for executing a task repeatedly with the actual execution time of the previous one, that is, scheduledexecutiontime (n + 1 times) = realexecutiontime (n times) + periodtime. That is to say, if the execution time of the nth task is too long for some reason, and the systemcurrenttime> = scheduledexecutiontime (n + 1) After the execution is completed, no wait is performed at this time, execute the n + 1 task immediately, and the scheduledexecutiontime (n + 2) of the next n + 2 task changes to realexecutiontime (n + 1) + periodtime. To put it bluntly, this method focuses more on maintaining the stability of the interval.
(3) When the scheduleatfixedrate of the three parameters is formulated to execute a task repeatedly, the execution time of each plan for executing the task is initially determined, that is, scheduledexecutiontime (n times) = firstexecutetime + N * periodtime; if the n times of task execution, for some reason, this execution time is too long, after the execution, systemcurrenttime> = scheduledexecutiontime (n + 1 times). At this time, do not wait at the period interval. Execute the n + 1 task immediately, however, the scheduledexecutiontime (n + 2) of the next n + 2 tasks is still firstexecutetime + (n + 2) * periodtime, which is determined after the first task is executed. To put it bluntly, this method focuses more on maintaining a stable execution frequency.

5. Notes
Each timer corresponds to only one thread.
Timer does not guarantee that the task execution is very accurate.
Timer class thread security.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.