Java.util.Timer is similar to an alarm clock scheduled to do tasks

Source: Internet
Author: User

Implementing a task plan in the Web is equivalent to implementing an alarm clock, which is accomplished in 2 steps:

1, the setting of the timer;

2. Real-time monitoring of the timer's start-up operation and stop

The Java.util.Timer timer, which is actually a thread, is scheduled to be owned by the Timertasks

A timertask is actually a class that has a run method, and the code that needs to be executed regularly is put into the Run method body, TimerTask is generally created as an anonymous class.

Timer is a kind of thread facility, which can be used to arrange the task that will be executed in background thread, schedule the task to execute once, or repeat it periodically, can be regarded as a timer, scheduling timertask,timertask is an abstract class, realizes the Runnable interface, So have the ability of multithreading.

The Timer class uses Java.util.TaskQueue to add tasks at specified intervals and only one thread can execute timertask at the time of the task.

The Timer class uses the object's wait and notify methods to dispatch the task, and the timer object will continue to add the task to the queue, and once the task has ended, it will notify the queue and another thread will start execution.

A timer is a timed dispatch class in the JDK that is mostly timed to trigger a task:

Timer is a dispatch controller, TimerTask is a scheduled task

2. 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.

There are 4 schedule overloaded functions in a timer, and there are two scheduleatfixedrate:
void Scheduleatfixedrate (timertask task, Date Firsttime, long period)
Schedules the specified task to start at a fixed rate of repetition at a specified time.
void Scheduleatfixedrate (timertask task, long delay, long period)
Schedules the specified task to begin repeating a fixed rate of execution after a specified delay.
With Scheduleatfixedrate, the timer will try to keep the task running at a fixed frequency. For example, in the example above, let Secondtask be executed every 3 seconds after 1 seconds, but because Java is not real-time, the semantics we expressed in the last program are not strictly enforced, for example, sometimes the resource is dispatched for 4 seconds before the next, and sometimes 3.5 seconds, execution. If we call Scheduleatfixedrate, then the timer will try to keep your secondtask execution frequency at 3 seconds. Run the above program, assuming that the use of scheduleatfixedrate, then the following scenario is possible: after 1 seconds, Secondtask executes once, because the system is busy, After the next 3.5 seconds, Secondtask is able to execute the second time, then the timer notes the delay and tries to compensate for the delay on the following task, 2.5 seconds after the Secondtask will execute three times. "This is what it means to perform a task at a fixed frequency instead of a fixed delay time."
problem with timer termination:
By default, the program stays running as long as a program's timer thread is running. You can terminate a timer thread in one of the following 3 ways:
(1) Call the timer's Cancle method. You can call this method from anywhere in the program, even in a timer task's Run method;
(2) 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 thread, it will automatically terminate the operation;
(3) Call the System.exit method to terminate the entire program (all threads).
TimerTask also has a Cancel method.
As stated above, "as long as a program's timer thread is running, the program will remain running." So in turn, if all the timertask in the timer are executed, the entire program exits, and the test answer is no, such as the test code above, if only the first timertask is executed in the timer:
Timer.schedule (New MyTask (1), 5000);//5 Seconds to start the task
Then 5 seconds later, in fact, the whole program still does not quit, the timer will wait for garbage collection when it is recycled and then the program will be able to quit, but how long? After the execution of the TimerTask run function is completed, addSystem.GC ();You can do it.

The code is as follows:

Package test;

Import Java.util.Timer;
Import Java.util.TimerTask;


public class Timertest {

/**
* @param args
*/
public static void Main (string[] args) throws Java.io.IOException {

TimerTask task=new TimerTask () {

@Override
public void Run () {
System.out.println ("Hello");

}

};
Timer timer=new timer ();
Timer.schedule (task, 0,5000); 0 identifies the time to delay, and 5000 refers to milliseconds
}

}

is the TimerTask class, in the package: import Java.util.TimerTask. The consumer inherits the class and implements the public void run () method to encapsulate the task to be run into its run method. Because the TimerTask class implements the Runnable interface.

    1. Timer class: Set the parameters of the timer, including the start time, interval time, time delay, details see schedule method.
    2. Note: The same TimerTask object cannot be added to the timer twice, and if you have more than one task to execute, you need to declare multiple instances of TimerTask.

The second parameter "0" means: (0 means no delay)
When you call this method, the method is bound to call the run () method in the TimerTask class TimerTask class, which is the difference between the time between the two, that is, after the user calls the schedule () method, it takes such a long time to execute the run () party for the first time. Method.

The third parameter, "60*60*1000", means:
(Unit is in milliseconds 60*60*1000 for one hour)
(in milliseconds 3*60*1000 to three minutes)
After the first call, the run () method is called once every number of times from the second start.

Java.util.Timer is similar to an alarm clock scheduled to do tasks

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.