Add a timer to a java web Program

Source: Internet
Author: User

This Is My Timer class, used to regularly execute a certain task;

Package com. my. time;

Import java. text. ParseException;

Import java. text. SimpleDateFormat;

Import java. util. Date;

Import java. util. Timer;

Public class BugXmlTimer {

Public Timer timer;

Public void timerStart (){

Timer = new Timer ();

Date datetime = new Date ();

Date midnightDate = new Date ();

SimpleDateFormat sdf1 = new SimpleDateFormat ("yyyy-MM-dd ");

SimpleDateFormat sdf2 = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");

Try {

MidnightDate = sdf2.parse (sdf1.format (datetime) + "23:00:00 ");

} Catch (ParseException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

Long in = midnightDate. getTime ()-datetime. getTime ();

System. out. println ("before task ");

// Execute immediately, and then execute every 30 s

Timer. schedule (new BugXmlTimerTask (), 0,30000 );

}

Public void timerStop (){

If (timer! = Null)

Timer. cancel ();

}

Public static void main (String [] args ){

BugXmlTimer myTimer = new BugXmlTimer ();

// TODO Auto-generated method stub

MyTimer. timerStart ();

}

}

// This is the class for executing tasks, that is, the tasks to be done at intervals are shown here

Package com. my. time;

Import java. util. TimerTask;

Public class BugXmlTimerTask extends TimerTask {

@ Override

Public void run (){

System. out. print ("run task ");

}

}

// The following is a scheduled operation class, which implements ServletContextListener

Public class MyTimerListener implements ServletContextListener {

Private BugXmlTimer mytimer = new BugXmlTimer ();

Public void contextInitialized (ServletContextEvent event ){

Mytimer. timerStart ();

}

Public void contextDestroyed (ServletContextEvent event ){

Mytimer. timerStop ();

}

}

Then deploy it in web. xml to run the timer after the program starts!

<Listener>

<Listener-class> com. my. time. MyTimerListener </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.