Java timed task test inheritance TimerTask

Source: Internet
Author: User
First, introduce Java Timers (Java.util.Timer)The ability to perform scheduled tasks on a scheduled basis is automatically performed after this interval by setting the time interval of the timer Pre-arranged tasks (java.util. TimerTask)

Such as: Perform tasks every one hours timer.schedule (timertask, 0, 60 * 60 * 1000).

of the schedule () method

The first parameter is the task that needs to be performed, the type of this class is Java.util.TimerTask,

The second parameter is the wait time before the task is executed, where 0 means no wait, and the third parameter is the interval, in milliseconds.

/**  * Timed Task Test class  * @author admin  *  */public class Timerscheduledemo extends TimerTask {  public Timerscheduledemo () {}  @Override public void Run () {print ();}  public static void Main (string[] args) {Timer timer = new timer (); Long delay1 = 1 * n; long period1 = 1000;//starting from now 1 * After 1000 seconds, the timer.schedule is executed every 1 seconds (new Timerscheduledemo (), Delay1, PERIOD1); /*long delay2 = 2 * 1000; Long period2 = 2000; Timer.schedule (New Timerscheduledemo (), Delay2, PERIOD2) is executed every 2 seconds after 2 seconds from now; */} public static void print () {System.out.println ("method Start");}}

But:

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.

The main business code of the task class

/** * Timer Task class: Dispatch Task class * @author admin */public class Delfiletask extends timertask{    private static Boolean isrunning = f Alse;            Private ServletContext context = null;            Public Delfiletask () {          super ();      }            Public Delfiletask (ServletContext context) {            This.context = context;        }        @Override public      Void Run () {                    if (!isrunning) {                             context.log ("Start execution of specified tasks");               /**              * Own business code *              /                            isrunning = false;                Context.log ("Specify end of Task execution");          } else {                Context.log ("Last task execution was not finished");}}}   

This class is basically inheriting timertask and implementing its Run method.

Here is the listener class to start the listener server and add the task to the task stack

/** * servlet Listener: Perform dispatch task when listening service starts * @author Admin * */public class Contextlistener implements Servletcontextlistener{public C               Ontextlistener () {} private Java.util.Timer Timer = null; /** * Initialize timer * Web Program load automatically */@Override public void contextinitialized (Servletcontextevent a                        RG0) {/** * Set a timer */timer = new Java.util.Timer (true);               Arg0.getservletcontext (). Log ("timer started");           /** * Timer to a specified time, perform an action (such as a class, or method) *//Set Execution time calendar calendar =calendar.getinstance ();          int year = Calendar.get (calendar.year);          int month = Calendar.get (calendar.month); int day =calendar.get (calendar.day_of_month);//daily//Custom 16:10:00 execution, Calendar.set (year, MONTH, day, 16,          10, 00);          Date date = Calendar.gettime ();                  SYSTEM.OUT.PRINTLN (date);          int period = 1000; Execute TA at date time of daySK, repeated execution of Timer.schedule (new Delfiletask (Arg0.getservletcontext ()), date, period every persion time);                    Executes a task at the specified date time, executing only once//timer.schedule (new Delfiletask (Arg0.getservletcontext ()), date);                  Arg0.getservletcontext (). log ("The task schedule has been added"); }/** * Destroy * * @Override public void contextdestroyed (Servletcontextevent arg0) {time          R.cancel ();      Arg0.getservletcontext (). log ("timer destruction"); }  }

This class is mainly to set up a scheduler and let him follow certain requirements to perform the task.

The task class listener class implements the next step is to configure the listener on the Web. xml

  <listener>  <listener-class>ContextListener</listener-class>  </listener>

Here, a simple timer is basically realized, and it can run through.

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.