Use of the Java Timer (timer)

Source: Internet
Author: User
Tags repetition terminates

Transferred from: http://blog.csdn.net/ecjtuxuan/article/details/2093757

————————————————————————————————————————

1, in the application development, often need some periodic operation, such as every 5 minutes to perform a certain operation.

The most convenient and efficient way to do this is to use the Java.util.Timer tool class.

Private Java.util.Timer Timer;

Timer = new timer (true);

Timer.schedule (

New Java.util.TimerTask () {public void run ()

{//server.checknewmail (); methods to Operate}}, 0, 5*60*1000);

The first argument is the method to be manipulated, the second parameter is the time to set the delay, the third parameter

Number is the setting of the period, how often it is performed.

After using these lines of code, the timer itself will be called once every 5 minutes

Server.checknewmail () method, you do not need to start the thread yourself. The timer itself is also multithreaded with

, multiple threads can share a timer without the need for external synchronization code.

2.

(1) Timer.schedule (TimerTask task,date time) to schedule the execution of the specified

Task.

(2) Timer.schedule (TimerTask task,date firsttime, long period) schedule the specified

The task starts at a specified time and repeats a fixed deferred execution.

(3) Timer.schedule (timertask task,long delay) Schedules the specified delay to execute after the specified

Task

(4) Timer.schedule (TimerTask task,long Delay,long period) to schedule a specified task

Repeats a fixed deferred execution starting after the specified delay.

(5) Timer.scheduleatfixedrate (TimerTask task,date Firsttime,long period)

Schedules the specified task to start at a fixed rate of repetition at a specified time.

(6) Timer.scheduleatfixedrate (TimerTask task,long delay,long period) Ann

The specified task executes at a fixed rate that repeats after the specified delay.

with Java Timer API for time scheduling development of the relevant points of attention

Java.util This package can find the timer and the TimerTask two classes. Timer directly from Object

inheritance, which is equivalent to a timer that can be used to specify a time to perform a task, or

Perform the same task repeatedly at a certain interval of time. Once a timer is created, a thread is generated

Run in the back to control the execution of the task. And TimerTask is the class used to accomplish a task,

It implements the Runnable interface, and therefore the equivalent of a thread.

How do you implement your own Task Scheduler?

1, inherit timertask, note that TimerTask is the implementation of runnable interface, so as long as the overloaded run ()

Method can be used.

2. Create a Timer object and call the schedule () method.

Related points of attention analysis:

1, task scheduling should give priority to real-time guarantee

Because of the nature of Java, and in the process of developing the JDK to take into account different platforms, and different platforms

Thread scheduling mechanism is different, so the JVM's thread scheduling mechanism under various platforms is inconsistent.

Thus the timer cannot guarantee that the task executes within the specified time. In addition, because TimerTask is implemented

Runnable interface, after TimerTask is put into the thread queue for a period of sleep (wait),

When the timertask is called to the specified time, the exact timing of execution depends on the JVM's scheduling policy

And how many threads are still waiting for CPU processing. Therefore, there is no guarantee that the task will be at the specified time

Internal execution. There are typically two scenarios in which the task is delayed execution:

(1), there are a large number of threads waiting to execute

(2), the effect of GC mechanism causes delay

This is why there are two sets of scheduling methods in the Timer API. That

(1), schedule ()

Scheduling with fixed delays. When you use this method, each delay in the execution of a task is propagated to any subsequent

Implementation of the services.

(2), Scheduleasfixedrate ()

Scheduling with fixed ratios. When using this method, all subsequent executions are scheduled according to the initial execution time,

So you want to reduce latency.

The specific method you use depends on which parameters are more important to your program or system.

2, each Timer object to start a thread in the background. This property is not pushed in some managed environments

Applications, such as in the application server. Because these threads are not within the control of the container.

The Timer class and the TimerTask class in the specific Java API are described below:

Java.util

class Timer

Java.lang.Object

Java.util.Timer

public class Timer

Extends Object

A thread facility that is used to schedule tasks to be performed later in a background thread. You can schedule a task to execute once,

or repeat them on a regular basis.

corresponding to each Timer object is a single background thread, which is used to perform all timer tasks sequentially.

The timer task should be completed quickly. If the time to complete a timer task is too long, it will "

The task execution thread for the timer. As a result, this may delay the execution of subsequent tasks, and these tasks

May be "stacked together" and can be quickly and continuously in the final completion of the above-mentioned unpleasant tasks

To execute.

After the last reference to the Timer object is complete, and all outstanding tasks are completed, the

The task execution thread of the timer terminates normally (and becomes the object of garbage collection). But it's probably going to be

Occurs after a long time. By default, the task execution thread does not run as a daemon thread , so

It can prevent the application from terminating. If the caller wants to quickly terminate the task execution thread of the timer, that

The caller should invoke the timer's Cancel method.

If the task execution thread of the timer is unexpectedly terminated, for example by calling its Stop method, then all

Subsequent attempts to schedule a task on that timer will cause illegalstateexception, as if invoking the

The Cancel method of the timer.

This class is thread-safe: Multiple threads can share a single Timer object without having to synchronize externally.

This class does not provide a real-time guarantee: It uses the object.wait (long) method to schedule tasks.

Implementation considerations: This class can be extended to a large number of simultaneous scheduled tasks (there are thousands of of them without problems).

Internally, it uses a binary heap to represent its task queue, so the overhead of scheduling a task is O (log n),

where n is the number of tasks scheduled at the same time.

Implementation considerations: All construction methods start the timer thread.

Start from the following versions:

1.3

See also:

TimerTask, object.wait (Long)

Construction Method Summary

Timer ()

Creates a new timer.

Timer (Boolean Isdaemon)

Creates a new timer that specifies its associated thread to run as a daemon.

Timer (String name)

Creates a new timer whose associated thread has the specified name.

Timer (String name, Boolean Isdaemon)

Creates a new timer whose associated thread has the specified name and can be specified as a daemon to be shipped

Yes.

Method Summary

void Cancel()

Terminates this timer, discarding all currently scheduled tasks.

int purge()

Removes all canceled tasks from this timer's task queue.

void Schedule(timertask task, Date time)

Schedules the specified task to execute at the specified time.

void Schedule(timertask task, Date Firsttime, long period)

Schedules the specified task to begin repeating fixed deferred execution at a specified time.

void Schedule(timertask task, long delay)

Schedules the specified task to execute after a specified delay.

void Schedule(timertask task, long delay, long period)

Schedules the specified task to start repeating fixed deferred execution from the specified delay.

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.

from the class Java.lang. Object Methods of Inheritance

Clone, Equals, Finalize, GetClass, Hashcode, notify, Notifyall, toString, wait, wait, wait

Construction Method Details

Timer

Public Timer ()

Creates a new timer. The associated thread is not running as a daemon.

See also:

Thread, Cancel ()

Timer

Public Timer (Boolean Isdaemon)

Creates a new timer that specifies its associated thread to run as a daemon. If the timer will be used to

When you schedule a duplicate maintenance activity, the daemon thread is invoked, and the daemon thread must be called during the application's run.

However, the operation should not prolong the life cycle of the program.

Parameters:

Isdaemon-True if the related thread should be run as a daemon.

See also:

Thread, Cancel ()

Timer

Public Timer (String name)

Creates a new timer whose associated thread has the specified name. The associated thread is not shipped as a daemon

Yes.

Parameters:

Name-the names of the related threads.

Thrown:

NullPointerException-if name is null.

Start from the following versions:

1.5

See also:

Thread.getname (), Thread.isdaemon ()

Timer

Public Timer (String name,

Boolean Isdaemon)

Creates a new timer whose associated thread has the specified name and can be specified as a daemon to be shipped

Yes.

Parameters:

Name-the names of the related threads.

Isdaemon-True if the related thread should be run as a daemon.

Thrown:

NullPointerException-if name is null.

Start from the following versions:

1.5

See also:

Thread.getname (), Thread.isdaemon ()

Method details

Schedule

public void Schedule (TimerTask task,

Long delay)

Schedules the specified task to execute after a specified delay.

Parameters:

Task-the tasks that you want to schedule.

Delay-the time, in milliseconds, before the task is executed.

Thrown:

IllegalArgumentException-If delay is a negative number, or delay +

System.currenttimemillis () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, or the timer has been canceled.

Schedule

public void Schedule (TimerTask task,

Date time)

Schedules the specified task to execute at the specified time. If this time has passed, schedule the task to execute immediately.

Parameters:

Task-the tasks that you want to schedule.

Time-When the task was executed.

Thrown:

IllegalArgumentException-If Time.gettime () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, the timer has been canceled, or the timing

The device thread has terminated.

Schedule

public void Schedule (TimerTask task,

Long delay,

Long period)

Schedules the specified task to start repeating fixed deferred execution from the specified delay. At an approximate fixed time

Interval (delimited by the specified period) for subsequent execution.

In a fixed deferred execution, each execution is scheduled based on the actual execution time of the previous execution. Such as

For any reason (such as a garbage collection or other background activity), the

The continuation of the implementation will also be delayed. In the long run, the frequency of execution is generally slightly slower than the specified period of the inverted

Number (assuming that the system clock on which object.wait (long) depends is accurate).

Fixed-delay execution applies to repetitive activities that require "smooth" running. In other words, it fits

It is more important to keep the frequency accurate in the short run than in the long run. This bag

Include most animation tasks, such as a blinking cursor at a fixed time interval. This also includes responding to human

The fixed activity performed by the activity, such as automatically repeating the input character when the key is pressed.

Parameters:

Task-the tasks that you want to schedule.

Delay-the time, in milliseconds, before the task is executed.

Period-the time interval between each successor task, in milliseconds.

Thrown:

IllegalArgumentException-If delay is a negative number, or delay +

System.currenttimemillis () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, the timer has been canceled, or the timing

The device thread has terminated.

Schedule

public void Schedule (TimerTask task,

Date Firsttime,

Long period)

Schedules the specified task to begin repeating fixed deferred execution at a specified time. To approximate fixed time between

Intervals (separated by the specified period) for subsequent execution.

In a fixed deferred execution, each execution is scheduled based on the actual execution time of the previous execution. Such as

For any reason (such as a garbage collection or other background activity), the

The continuation of the implementation will also be delayed. In the long run, the frequency of execution is generally slightly slower than the specified period

The countdown (assuming that object.wait (long) depends on the system clock is accurate).

Fixed deferred execution is for repetitive execution activities that require "smooth" running. Other words

It is suitable for activities that are more accurate in the short run than those that are more important in the long run.

This includes most animation tasks, such as the blinking cursor at fixed intervals. This also includes a response

Fixed activities performed by human activities, such as the automatic repetition of input characters when holding down a key.

Parameters:

Task-the tasks that you want to schedule.

Firsttime-time when the task was first executed.

Period-the time interval between each successor task, in milliseconds.

Thrown:

IllegalArgumentException-If Time.gettime () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, the timer has been canceled, or the timing

The device thread has terminated.

Scheduleatfixedrate

public void Scheduleatfixedrate (TimerTask task,

Long delay,

Long period)

Schedules the specified task to begin repeating a fixed rate of execution after a specified delay. At an approximate fixed time

Interval (delimited by the specified period) for subsequent execution.

In a fixed rate execution, each execution is scheduled according to the scheduled initial execution time. If the

Delay a execution for any reason, such as garbage collection or other background activity, it will quickly

There are two or more executions in succession, so that subsequent executions can "catch up". From long

In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming object.wait (long)

Depends on the system clock is accurate).

Fixed rate execution applies to repetitive execution activities that are sensitive to absolute time, such as hourly quasi-

Or run scheduled maintenance activities at specific times of the day. It also applies To

Repetitive activities that are important to complete the total time of a fixed number of executions, such as Countdown timings

The device, ticks once every second for a total of 10 seconds. Finally, fixed rate execution applies to scheduling multiple

Recurring timer tasks that must be kept in sync with each other.

Parameters:

Task-the tasks that you want to schedule.

Delay-the time, in milliseconds, before the task is executed.

Period-the time interval between each successor task, in milliseconds.

Thrown:

IllegalArgumentException-If delay is a negative number, or delay +

System.currenttimemillis () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, the timer has been canceled, or the timing

The device thread has terminated.

Scheduleatfixedrate

public void Scheduleatfixedrate (TimerTask task,

Date Firsttime,

Long period)

Schedules the specified task to start at a fixed rate of repetition at a specified time. To approximate fixed time between

Intervals (separated by the specified period) for subsequent execution.

In a fixed rate execution, each execution is scheduled relative to the scheduled initial execution time. If

Delay a execution for any reason, such as garbage collection or other background activity, it will quickly

Two or more times in a row, enabling subsequent execution to catch up. In the long run.

See, the frequency of execution will be exactly the reciprocal of the specified period (assuming that object.wait (long)

Depends on the system clock is accurate).

Fixed rate execution applies to repetitive execution activities that are sensitive to absolute time, such as hourly quasi-

Or run scheduled maintenance activities at specific times of the day. It also applies To

Repetitive activities that are important to complete the total time of a fixed number of executions, such as Countdown timings

The device, ticks once every second for a total of 10 seconds. Finally, the fixed rate execution applies to scheduling multiple

Recurring timer tasks that must be kept in sync with each other.

Parameters:

Task-the tasks that you want to schedule.

Firsttime-time when the task was first executed.

Period-the time interval between each successor task, in milliseconds.

Thrown:

IllegalArgumentException-If Time.gettime () is a negative number.

IllegalStateException-If the task has been scheduled or canceled, the timer has been canceled, or the timing

The device thread has terminated.

Cancel

public void Cancel ()

Terminates this timer, discarding all currently scheduled tasks. This does not interfere with the tasks that are currently being performed, such as

The presence of the fruit). Once the timer is terminated, its execution thread is terminated, and it is not possible to schedule more

Multi-tasking.

Note that this method is called within the Run method of the timer task called by this timer, and you can

Absolutely ensure that the task you are performing is the last task that this timer performs.

This method can be called repeatedly, but the second and subsequent calls are not valid.

Purge

public int Purge ()

Removes all canceled tasks from this timer's task queue. The behavior of calling this method on a timer does not

, you will not be able to reference the canceled task in the queue. If there are no external references to these tasks, the

They become eligible objects for garbage collection.

Most programs do not need to call this method. It is designed to be used in rare applications where these programs can be

Cancel a large number of tasks. Call this method to exchange space for time: The runtime of this method may

is proportional to n + C log n, where n is the number of tasks in the queue, and C is the cancellation of any

The number of services.

Note that calling this method is allowed on tasks scheduled from this timer.

Return:

The number of tasks to remove from the queue.

Start from the following versions:

1.5

The following is an introduction to the TimerTask class

Java.util

class TimerTask

Java.lang.Object

Java.util.TimerTask

All implemented interfaces:

Runnable

Public abstract class TimerTask

Extends Object

Implements Runnable

A task that is scheduled to be performed or performed repeatedly by a timer.

Start from the following versions:

1.3

See also:

Timer

Construction Method Summary

Protected timertask()

Creates a new timer task.

Method Summary

Boolean cancel()

Cancels this timer task.

abstract void Run()

The action to be performed by this timer task.

Long scheduledexecutiontime()

Returns the schedule execution time that this task has recently actually performed.

from the class Java.lang. Object Methods of Inheritance

Clone, Equals, Finalize, GetClass, Hashcode, notify, Notifyall, toString, wait, wait, wait

Construction Method Details

TimerTask

Protected TimerTask ()

Creates a new timer task.

Method details

Run

public abstract void Run ()

The action to be performed by this timer task.

Designated by:

Run in the interface runnable

See also:

Thread.run ()

Cancel

public boolean cancel ()

Cancels this timer task. If the task is scheduled for a single execution and is not yet running, or has not been scheduled, always

Will not run. If the task is scheduled to execute repeatedly, it will never run again. (If this call occurs, the task

is running, the task will run out, but will never run again. )

Note that calling this method from the run method of the repeating timer task absolutely guarantees that the timer

Service will never run again.

This method can be called repeatedly, and the second and subsequent invocations are invalid.

Return:

Returns true if this task is scheduled to execute once and has not been run, or if the task is scheduled to be repeated.

If the task is scheduled to be executed once and is already running, or if the task has not been scheduled, or the task has been taken

Returns False if it is eliminated. (Generally, if this method prevents one or more scheduled executions from occurring, it returns

True )

Scheduledexecutiontime

Public long Scheduledexecutiontime ()

Returns the schedule execution time that this task has recently actually performed. (If this method is called during task execution,

The return value is the scheduled execution time that is performed for this task. )

This method is typically called from the Run method of a task to determine whether the current task execution can

Ensure full and timely completion of scheduled activities:

public void Run () {

if (System.currenttimemillis ()-Scheduledexecutiontime ()

>=

max_tardiness)

Return Too late; Skip this execution.

Perform the Task

}

Typically, this method is not used with repetitive tasks that are performed with fixed delays , because their scheduled execution time allows

Float over time, so it makes no sense.

Return:

The time that this task has recently been scheduled to execute, in the format returned by Date.gettime (). If the task is already open

Initial execution, the return value is indeterminate.

Use of the Java Timer (timer)

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.