Java multithreading BASICS (2) Timer class: Timer class and TimerTask class, timertimertask class
Java multithreading BASICS (2) Timer class: Timer class and TimerTask class
Timer class and TimerTask class are early methods for jdk to implement the Timer function. jdk1.5 previously supported Timer class and TimerTask class. After JDK, a new mechanism is introduced, which will be studied in subsequent blog posts.
1. Execute the task after the specified time interval
Import java. util. date; import java. util. timer; import java. util. timerTask; public class TraditionalTimerTest {public static void main (String [] args) {// start the Timer thread, and execute the run method new Timer () of the TimerTask instance after 10000 milliseconds (). schedule (new TimerTask () {@ Override public void run () {System. out. println ("bombing! ") ;}}, 10000); while (true) {System. out. println ("clock time:" + new Date (). getSeconds (); try {Thread. sleep (1000); // The main thread prints the current clock time every second} catch (InterruptedException e) {e. printStackTrace ();}}}}
The source code of the main java API called and java doc:
public void schedule(TimerTask task, long delay) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); }
Schedules the specified task for execution after the specified delay.
Schedule the task to be executed after the specified delay.
Parameters:
Task-task to be scheduled.
Delay-delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException-if delay is negative, or delay + System. currentTimeMillis () is negative.
IllegalStateException-if task was already scheduled or canceled, timer was canceled, or timer thread terminated.
NullPointerException-if task is null
2. execute tasks cyclically after the specified time interval
Import java. util. date; import java. util. timer; import java. util. timerTask; public class TraditionalTimerTest {public static void main (String [] args) {// start the timer thread and start after 10000 milliseconds, the scheduled task is executed every 3000 milliseconds. new Timer (). schedule (new TimerTask () {// scheduled task @ Override public void run () {System. out. println ("bombing! ") ;}}, 10000,300 0); while (true) {System. out. println ("clock time:" + new Date (). getSeconds (); try {Thread. sleep (1000); // The main thread prints the current clock time every second} catch (InterruptedException e) {e. printStackTrace ();}}}}
The source code of the main java API called and java doc:
public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); }
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
Schedule the specified task to start repeated fixed delays after the specified delay. Perform subsequent execution at an approximate fixed interval (separated by a specified period.
In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. if an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. in the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object. wait (long) is accurate ).
In fixed latency execution, each execution is scheduled based on the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activities), subsequent execution will also be delayed. In the long run, the execution frequency is generally slightly slower than the countdown of the specified period (assuming that the system clock relied on by Object. wait (long) is accurate ).
Fixed-delay execution is appropriate for recurring activities that require "smoothness. "In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. this includes des most animation tasks, such as blinking a cursor at regular intervals. it also shortdes tasks wherein regular activity is saved med in response to human input, such as automatically repeating a character as long as a key is held down.
Fixed latency execution applies to repetitive activities that require "stable" operation. In other words, it is applicable to activities that are more frequent and accurate than long-term operations. This includes most animation tasks, such as flashing the cursor at a fixed interval. This also includes fixed activities performed in response to human-machine input, such as automatically repeating input characters when pressing the key.
Parameters:
Task-task to be scheduled.
Delay-delay in milliseconds before task is to be executed.
Period-time in milliseconds between successive task executions.
Throws:
IllegalArgumentException-if delay <0, or delay + System. currentTimeMillis () <0, or period <= 0
IllegalStateException-if task was already scheduled or canceled, timer was canceled, or timer thread terminated.
NullPointerException-if task is null
3. More flexible Interval
Every 2 seconds, 4 seconds, 2 seconds, 4 seconds ,..., Execute tasks cyclically.
Method 1 define a TimerTask class
Import java. util. date; import java. util. timer; import java. util. timerTask; public class TraditionalTimerTest {static int count = 0; public static void main (String [] args) {class MyTimerTask extends TimerTask {@ Override public void run () {count = (count + 1) % 2; // customizes the System at different intervals. out. println ("bombing! "); New Timer (). schedule (new MyTimerTask (), // recursively instance the new scheduled task 2000 + 2000 * count);} new Timer (). schedule (new MyTimerTask (), 2000); while (true) {System. out. println ("clock time:" + new Date (). getSeconds (); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();}}}}
Method 2 defines two/more TimerTask classes
Import java. util. date; import java. util. timer; import java. util. timerTask; public class TraditionalTimerTest {public static void main (String [] args) {new Timer (). schedule (new MyTimerTask1 (), 2000); while (true) {System. out. println ("clock time:" + new Date (). getSeconds (); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}}} class MyTimerTask1 extends TimerTask {@ Override public void run () {System. out. println ("Task1"); new Timer (). schedule (new MyTimerTask2 (), 2000); // start scheduled task 2} class MyTimerTask2 extends TimerTask {@ Override public void run () {System. out. println ("Task2"); new Timer (). schedule (new MyTimerTask1 (), 4000); // start scheduled Task 1 }}
4. Other common Timer APIs
Return Value |
Method Signature |
Void |
Schedule (TimerTask task, Date time) Schedules the specified task for execution at the specified time. Schedule the task to be executed at the specified time. If the time has passed, the task is scheduled to be executed immediately. |
Void |
Schedule (TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Schedule the specified task to repeat at the specified timeFixed latency execution. Perform subsequent execution at an approximate fixed interval (separated by a specified period.
In fixed latency execution, each execution is scheduled based on the actual execution time of the previous execution. If the execution is delayed for any reason (such as garbage collection or other background activities,The subsequent execution will also be delayed.. In the long-term operation, the execution frequency is generally slightly slower than the countdown of the specified period (assuming that the system clock relied on by Object. wait (long) is accurate ).
Fixed latency execution applies to Repetitive execution activities that require "stable" operation. In other words, it is applicable to activities that are more frequent and accurate than long-term operations. This includes most animation tasks, such as flashing the cursor at a fixed interval. This also includes fixed activities executed to respond to human activities, such as automatically repeating input characters when holding down the key. |
Void |
Schedule (TimerTask task, long delay) Schedules the specified task for execution after the specified delay. Schedule the task to be executed after the specified delay. |
Void |
Schedule (TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Schedule the specified task to start repeating after the specified DelayFixed latency execution. Perform subsequent execution at an approximate fixed interval (separated by a specified period.
In fixed latency execution, each execution is scheduled based on the actual execution time of the previous execution. If the execution is delayed for any reason (such as garbage collection or other background activities,The subsequent execution will also be delayed.. In the long run, the execution frequency is generally slightly slower than the countdown of the specified period (assuming that the system clock relied on by Object. wait (long) is accurate ).
Fixed latency execution applies to repetitive activities that require "stable" operation. In other words, it is applicable to activities that are more frequent and accurate than long-term operations. This includes most animation tasks, such as flashing the cursor at a fixed interval. This also includes fixed activities executed to respond to human activities, such as automatically repeating input characters when holding down the key. |
Void |
ScheduleAtFixedRate (TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Schedule the specified task to repeat at the specified timeFixed Rate execution. Perform subsequent execution at an approximate fixed interval (separated by a specified period.
At a fixed rate, each execution is scheduled relative to the scheduled initial execution time. If an execution is delayed for any reason (such as garbage collection or other background activities), two or more executions will appear consecutively,So that subsequent execution can catch up. In the long run, the execution frequency is exactly the reciprocal of the specified period (assuming that the system clock relied on by Object. wait (long) is accurate ).
Fixed-rate execution is applicable to Repetitive execution activities that are sensitive to absolute time, such as hourly clock reporting or running scheduled maintenance activities at specific times of the day. It also applies to repetitive activities that are important to the total time for completing a fixed number of executions, such as countdown timers, ticking once per second for a total of 10 seconds. Finally, fixed-rate execution is suitable for timer tasks that are scheduled to be executed repeatedly. These tasks must be synchronized with each other. |
Void |
ScheduleAtFixedRate (TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Schedule the specified task to start repeating after the specified DelayFixed Rate execution. Perform subsequent execution at an approximate fixed interval (separated by a specified period.
At a fixed rate, each execution is scheduled Based on the scheduled initial execution time. If an execution is delayed for any reason (such as garbage collection or other background activities), two or more executions will appear consecutively,So that subsequent execution can "Catch Up". In the long run, the execution frequency is exactly the reciprocal of the specified period (assuming that the system clock relied on by Object. wait (long) is accurate ).
Fixed-rate execution is applicable to Repetitive execution activities that are sensitive to absolute time, such as hourly clock reporting or running scheduled maintenance activities at specific times of the day. It also applies to repetitive activities that are important to the total time for completing a fixed number of executions, such as countdown timers, ticking once per second for a total of 10 seconds. Finally, fixed-rate execution is suitable for Arranging multiple timer tasks for repeated execution. These tasks must be synchronized with each other. |
For more API details, refer to Java se api:
API: http://docs.oracle.com/javase/6/docs/api/index.html
English API: http://tool.oschina.net/apidocs/apidoc? Api = jdk-zh
More complex timers can use the quartz Library: http://www.quartz-scheduler.org/