Java timed data update --- Timer

Source: Internet
Author: User


In application development, periodic operations are often required, such as performing an operation every five minutes. This time, we have such a requirement in our development. if the execution of a function takes a long time, the timer is used. The system automatically runs this function at intervals. When the interface is actually triggered, you only need to simply read the result, no complicated logic judgment is required. how can this function be implemented? To implement it, first we need to understand several classes encapsulated by jdk.

Java. util. Timer: A thread facility used to schedule tasks to be executed in backend threads later. You can schedule tasks to be executed once or regularly run repeatedly. Pay attention to the following methods:

Cancel (): Terminate this timer and discard all tasks currently scheduled.

Schedule (TimerTask task, Date time): scheduled to run the specified task at the specified time.

Schedule (TimerTask task, Date firstTime, long period): schedule the specified task to start repeating fixed delay execution at the specified time.

Schedule (TimerTask task, long delay): scheduled to run the specified task after the specified delay.

Schedule (TimerTask task, long delay, long period): schedule the specified task to start repeated fixed delay execution after the specified delay.

ScheduleAtFixedRate (TimerTask task, Date firstTime, long period): Schedule the specified task to start repeating at a fixed rate.

ScheduleAtFixedRate (TimerTask task, long delay, long period): schedules a specified task to start repeated execution at a fixed rate after the specified delay.

In the Timer methods mentioned above, the TimerTask class is involved in the parameters. What is the TimerTask class doing? This is the task scheduled by Timer, that is, the task to be executed once or multiple times. The following methods in this class require more attention.

Cancel (): cancels this timer task.

Run (): the operation to be performed by this timer task. Here is the code implementation for specific operations.

 

Through the Timer and TimerTask classes, we can implement repeated execution of tasks. however, we have no starting and ending points for execution. we should not trigger the execution of tasks manually. We should use code to let the service execute the tasks by ourselves. in this way, we need a listener to monitor whether the current execution conditions are met. servletContextListener implements this function for us. this interface can monitor the lifecycle of a ServletContext object, which is actually the lifecycle of a Web application. when a Servlet container starts or terminates a Web application, the ServletContextEvent event is triggered and handled by ServletContextListener. the following two methods are involved:

ContextInitialized (ServletContextEvent sce); Initialization;

ContextDestroyed (ServletContextEvent sce) Destruction

Now, the preparation is complete. Let's take a look at how the timer is implemented.

[Java]
Package com. boco. transnms. server. bo. stat;
Import java. util. Date;
Import java. util. Timer;
Import java. util. TimerTask;
Import javax. servlet. ServletContextEvent;
Import javax. servlet. ServletContextListener;
Public class NFDFlightDataTaskListener implements ServletContextListener {
@ Override
Public void contextDestroyed (ServletContextEvent arg0 ){
// Code for destruction
}
@ Override
// Execute this method when the service is started.
Public void contextInitialized (ServletContextEvent arg0 ){
New TimerManager ();
}
}
// Task to be executed
Class NFDFlightDataTimerTask extends TimerTask {
@ Override
// This method is specific for scheduled operations
Public void run (){
System. out. println ("timer test:" + System. currentTimeMillis ());
}
}
Class TimerManager {
Private static final long PERIOD_DAY = 6*1000; // execute once every six seconds
Public TimerManager (){
Timer timer = new Timer (); // Timer instantiation
NFDFlightDataTimerTask task = new NFDFlightDataTimerTask (); // the task to be executed
// Schedule the specified task to execute at a fixed delay at a specified time.
Timer. schedule (task, new Date (), PERIOD_DAY );
}
}

Package com. boco. transnms. server. bo. stat;
Import java. util. Date;
Import java. util. Timer;
Import java. util. TimerTask;
Import javax. servlet. ServletContextEvent;
Import javax. servlet. ServletContextListener;
Public class NFDFlightDataTaskListener implements ServletContextListener {
@ Override
Public void contextDestroyed (ServletContextEvent arg0 ){
// Code for destruction
}
@ Override
// Execute this method when the service is started.
Public void contextInitialized (ServletContextEvent arg0 ){
New TimerManager ();
}
}
// Task to be executed
Class NFDFlightDataTimerTask extends TimerTask {
@ Override
// This method is specific for scheduled operations
Public void run (){
System. out. println ("timer test:" + System. currentTimeMillis ());
}
}
Class TimerManager {
Private static final long PERIOD_DAY = 6*1000; // execute once every six seconds
Public TimerManager (){
Timer timer = new Timer (); // Timer instantiation
NFDFlightDataTimerTask task = new NFDFlightDataTimerTask (); // the task to be executed
// Schedule the specified task to execute at a fixed delay at a specified time.
Timer. schedule (task, new Date (), PERIOD_DAY );
}
}
 

Since the listener is available when the service is started, the configuration file is not required. How is the web. xml configuration file configured?

[Html] view plaincopyprint? <Listener>
 
<! -Here is the complete package name class name for implementing the listener interface -->
 
<Listener-class>
 
Com. boco. transnms. server. bo. stat. NFDFlightDataTaskListener
 
</Listener-class>
 
</Listener>

<Listener>

<! -Here is the complete package name class name for implementing the listener interface -->

<Listener-class>

Com. boco. transnms. server. bo. stat. NFDFlightDataTaskListener

</Listener-class>

</Listener>

 

 

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.