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>