Summary of Java Web timed task scheduling

Source: Internet
Author: User
Tags dateformat

There is time we need the server in the dead of night, silently perform the dispatch task. The Java Tomcat-based scheduling task is performed in the following two ways (hands-on):

I. Realization of Servletcontextlistener class

1.SysContextListener Class (Configuration task timed scan)

1  PackageCom.srba.task;2 3 4 ImportJava.util.Timer;//Timer class5 6 Importjavax.servlet.ServletContextEvent;7 ImportJavax.servlet.ServletContextListener;8  Public classSyscontextlistenerImplementsServletcontextlistener9 { Ten   PrivateTimer timer =NULL;  One   //rewrite contextinitialized A    Public voidcontextinitialized (servletcontextevent event) -   {  -       //This is where the listener is initialized and the listener starts when Tomcat is started, where the timer function can be implemented theTimer =NewTimer (true);  -       //Add a log that you can view in the Tomcat log -Event.getservletcontext (). Log ("Timer started");  -SYSTEM.OUT.PRINTLN ("+++++++++++++++++++++++++++ system daily dispatch task is turned on, is protecting the earth security!" ++++++++++++++++++++++++++++"); +         inti=1000;//1000 milliseconds and 1 seconds -         ints=1000*60*60;//executes every 60 minutes (can be changed to 1000*2, scanned every 2 seconds) +Timer timer=NewTimer (); A          //invoking a timed task, I means that the task has no delay, s means that the task is performed every s millisecond, and the trigger interval is measured in milliseconds. 1 seconds =1000 milliseconds.  atTimer.schedule (Newtimeraction (event), I, s); -Event.getservletcontext (). Log ("added task");  -   }  -   //rewrite contextdestroyed -    Public voidcontextdestroyed (servletcontextevent event) -   {  in       //Close the listener here, so destroy the timer here.  - Timer.cancel (); toEvent.getservletcontext (). log ("Timer destroy"));  +   }  -}

2.TimerAction Class (Specific tasks to perform)

1  PackageCom.srba.task;2 3 4 Importjava.sql.SQLException;5 ImportJava.text.DateFormat;6 ImportJava.text.SimpleDateFormat;7 Importjava.util.Date;8 ImportJava.util.TimerTask;9 Ten Importjavax.servlet.ServletContextEvent; One  A Importcom.srba.web.AllUserInfoMaintenance; -  Public classTimeractionextendsTimerTask { -     Privateservletcontextevent MyEvent; the timeraction (Servletcontextevent event) { -          This. MyEvent =event; -     } -          Public voidrun () { +SimpleDateFormat sdf=NewSimpleDateFormat ("HH");//Can be changed to New SimpleDateFormat ("SS"), accurate to seconds   -DateFormat MyFormat =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); +             if(Sdf.format (NewDate ()). Equals ("01")) {//daily 01 o'clock in the morning ADate begindate =NewDate (); atMyevent.getservletcontext (). Log ("Now" "+myformat.format (begindate) +" starts the Sync task!) "); -Alluserinfomaintenance task =Newalluserinfomaintenance (); -                 Try { - task.doupdate (); -Date endDate =NewDate (); -Myevent.getservletcontext (). Log ("Now" "+myformat.format (endDate) +" "Executes the synchronization task at the end! "); in}Catch(SQLException e) { - e.printstacktrace (); to                 } +             } -         } the      *}

3. Add the following to the <web-app> node in the project's Web. XML (Note the path to the package):

  < Listener >     < Listener-class >          com.srba.task.SysContextListener     </listener-class> </ Listener >

The first method is happy to finish.
II. Realization of Applicationlistener<contextrefreshedevent> class

1.SrbaAutoTask class

1  PackageCom.srba.siss.rule.task;2 3 ImportJava.text.SimpleDateFormat;4 Importjava.util.Date;5 ImportJava.util.Timer;6 ImportJava.util.TimerTask;7 8 ImportJavax.annotation.Resource;9 Ten ImportOrg.springframework.context.ApplicationListener; One Importorg.springframework.context.event.ContextRefreshedEvent; A ImportOrg.springframework.stereotype.Service; -  - ImportCom.srba.siss.rule.service.SrbaRuleTaskService; the ImportCom.srba.siss.rule.service.SystemCurrencyService; -  - @Service -  Public classSrbaautotaskImplementsApplicationlistener<contextrefreshedevent> + {     - @Resource +     PrivateSrbaruletaskservice Srbaruletaskservice; A @Override at      Public voidonapplicationevent (Contextrefreshedevent event) { -         //TODO auto-generated Method Stub -         if(Event.getapplicationcontext (). getParent () = =NULL){ -SYSTEM.OUT.PRINTLN ("+++++++++++++++++++++++++++ system daily dispatch task is turned on, is protecting the earth security!" ++++++++++++++++++++++++++++"); -             inti=1000;//1000 milliseconds and 1 seconds -             ints=1000*60*60;//executes every 60 minutes inTimer timer=NewTimer (); -Timer.schedule (Newtimeraction (event), I, s); to         } +     } -  the      *  $ Panax Notoginseng}

2.TimerAction () class, 2 in the same.

3. Configure the Applicationcontext.xml file to add the following (after Tomcat starts the spring load completes, the following classes are automatically executed)

<!---    <base-package = " Com.srba.siss.rule.task "></context:component-scan>

The second scheduling method is also happy to configure the finished.

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 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.
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:
Boolean cancel ()
Cancels this timer task.
Long Scheduledexecutiontime ()
Returns the schedule execution time that this task has recently actually performed.

Summary of Java Web timed task scheduling

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.