[Common Java class libraries] _ scheduled scheduling notes
Objectives of this chapter:
Understand the role of timed scheduling.
Measure the test taker's knowledge about the roles of timer and timertask classes.
3. Details
Regular scheduling, each time at one end,ProgramIt is automatically executed, called scheduled scheduling.
If you want to use scheduled scheduling, you must ensure that the program is always running. That is to say, scheduled scheduling starts a new thread outside the program!
Timer and timetask perform scheduled scheduling.
Timer class
The timer class is a thread facility that can be used to schedule a task to be executed at a certain time or after a certain period of time, or to execute it regularly and repeatedly. This function must be used with timertask. The timertask class is used to implement one or more tasks scheduled by timer.
Each timer object corresponds to a thread, so the tasks executed by the timer should be completed quickly. Otherwise, subsequent tasks may be delayed, and these subsequent tasks may be stacked together, after the task is completed, the task can be executed continuously.
Difference between schedule () and scheduleatfixedrate () Methods
The difference between the two is that when you execute a task repeatedly, You Can troubleshoot the delay at the interval:
The execution interval of the Schedule () method is always fixed. If there is a delay, it will continue to be executed according to the set interval.
The scheduleatfixedrate () method can automatically adjust the execution time of the next interval based on the delay time.
InstanceCode(Print the current time at intervals ):
// Complete specific task operations
Import Java. util. timertask; import Java. util. date; import Java. text. simpledateformat; Class mytask extends timertask {// The task scheduling class must inherit timertask public void run () {simpledateformat SDF = NULL; SDF = new simpledateformat ("yyyy-mm-dd hh: MM: Ss. SSS "); system. out. println ("current system time:" + SDF. format (new date ()));}};
Import Java. util. timer; public class testtask {public static void main (string ARGs []) {timer T = new timer (); // create a Timer class Object mytask = new mytask (); // define task T. schedule (mytask,); // sets the execution of the task, which starts in 1 second and repeats every 2 seconds }};