The timer timer for Java

Source: Internet
Author: User

1. Principle

In the JDK, the execution of a timer task requires two basic classes: Java.util.timer;java.util.timertask;

The Java.util.Timer timer is actually a thread that 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, and timertask is typically created in the form of an anonymous class.

To run a scheduled task, the most basic steps are as follows:
1, establish a task to be performed timertask.
2, create a timer instance, through the timer provided by the schedule () method, the TimerTask is added to a timer timer, while setting the rules to execute.

The schedule () method in the timer is available in a number of overloaded formats to accommodate different situations. The format of the method is as follows:
void Schedule (TimerTask task, Date time) schedules the specified task to be executed at the specified times.
void Schedule (timertask task, Date Firsttime, long period) schedules the specified task to begin repeating a 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.

2. Explanation

The timer is thread-safe, and this class can be extended to a large number of simultaneous tasks (there are thousands of of them without problems). All of its construction methods start the timer thread. You can call Cancel () to terminate this timer and discard any currently scheduled tasks. Purge () removes all canceled tasks from this timer's task queue. This class does not provide a real-time guarantee: It uses the object.wait (long) method to schedule tasks.

TimerTask is an abstract class that is scheduled for a task to be executed or performed repeatedly by a Timer. It has an abstract method run ()----The action to be performed by the timer task. Therefore, each specific task class must inherit the TimerTask class and override the run () method. In addition, it has two non-abstract methods:
A Boolean cancel () cancels this timer task.
Long Scheduledexecutiontime () returns the schedule execution time that this task has recently actually performed.

3. Simple use in the Web

Because we hope that when the Web project starts, the timer can automatically start the timing, so throughout the Web project life time, will be scheduled to perform tasks, so the class to start the timer can not be a general class, here with the Servlet listener class to start the timer, by configuring this listener in the configuration file, Allow it to load automatically at the start of the project and survive for the entire Web project life cycle.

Add the following code to Web. XML:

<listener> <listener-class>sample.hello.resources.TimeListener</listener-class> </listener& Gt

The

Listener code is as follows:

package sample.hello.resources;import java.util.timer;import javax.servlet.servletcontextevent; import javax.servlet.servletcontextlistener;public class timelistener implements  servletcontextlistener{  private timer timer = null;  public  TimeListener ()  {  // todo auto-generated constructor stub } @ Override public void contextdestroyed (servletcontextevent arg0)  {  //  Todo auto-generated method stub        timer.cancel ();           arg0.getservletcontext (). log ("timer destroy");   }  @Override  public void contextinitialized (servletcontextevent arg0)  {   // TODO Auto-generated method stub             /**          *  Setting a timer            */          timer = new  timer (True);                     arg0.getservletcontext (). Log ("timer started");             /**          *  Timer to a specified time, perform an action (such as a class, or method)           */           //the last parameter represents the monitor's monitoring period            timer.schedule (New apptimetask (Arg0.getservletcontext ()),  0, 5000);             arg0.getservletcontext (). Log ("Task Scheduler added");   }}

Timed task code:

package sample.hello.resources;import java.util.timertask;import javax.servlet.servletcontext; Public class apptimetask extends timertask {     private  servletcontext context = null;     public apptimetask ()  {          super ();      }       public apptimetask (Servletcontext context)  {           this.context = context;      }        @Override      public void  Run ()  {      // TODO Auto-generated method stub                        *//**                       *  write code to execute task here                        *//*                       system.out.println ("====== ========= Timer Task method starts execution = = ");      }}

The timer timer for Java

Related Article

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.