Use of Listener and Timer in JSP

Source: Internet
Author: User

Other JSP articles:

Use the automatic Bean property filling mechanism in JSP

JSP: list server environment variables

Implementation Mechanism and Application of abnormal turning of JSP errorPage commands to error pages

Jsp uses the 404 error page to rewrite the URL

Sometimes you need to regularly execute some programs during JSP running, such as collecting traffic and updating cache data. Generally, Listener and Timer are used. The following is a simple application, the purpose is to check whether the program is being executed at any time.

Create a TimerTask

Public class LogTask extends TimerTask {
@ Override
Public void run (){
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
System. out. println (sdf. format (new Date () + "-- this programe is running! ");

}
}

Create a listener

Public class LogListener implements ServletContextListener {
Private Timer timer = null;
@ Override
Public void contextDestroyed (ServletContextEvent arg0 ){
// TODO Auto-generated method stub
If (timer! = Null)
{
Timer. cancel ();
}
}

@ Override
Public void contextInitialized (ServletContextEvent arg0 ){
// TODO Auto-generated method stub
If (timer = null)
{
Timer = new Timer ();
Timer. schedule (new LogTask (), new Date (), 1000 );
}
}

}

Configure in web. xml

<Listener>
<Listener-class> org. heroking. web. LogListener </listener-class>
</Listener>

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.