The first is the Servletcontextlistener class.
If you implement this interface, then add the XML configuration
<listener>
<listener-class>com.xxx.xxx.MyTimerTask</listener-class>
</listener>
This class will be loaded automatically when the Web project is published to Tomcat, and then the contextinitialized and contextdestroyed methods in it will be able to do what you want to do when the Web container is initialized and destroyed. Here we use it as the start timer and end timer.
Below the code directly on the timer
/*** Timer Task class *@authorXX **/ Public classMytimertaskImplementsservletcontextlistener{//Define a timer PrivateTimer timer =NULL; /*** Method of Destruction*/@Override Public voidcontextdestroyed (Servletcontextevent event) {timer.cancel (); System.out.println ("Timer Destruction"); Event.getservletcontext (). log ("Timer Destruction"); } /*** Method of Creation*/@Override 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 implementedTimer =NewTimer (true); System.out.println ("Timer has started"); Event.getservletcontext (). log ("Timer has been activated");//Add a log that you can view in the Tomcat log//calling exporthistorybean,0 indicates that the task has no delay, 5*1000 indicates that the task is performed every 5 seconds, 60*60*1000 represents one hours;//Timer.schedule (task,0,10*1000);Task Task=NewTask (); //represents the number of milliseconds in a day LongDayspan = 24 * 60 * 60 * 1000; FinalSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd ' 16:49:00 '"); Date StartTime=NewDate (); Try{startTime=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Parse (Sdf.format (NewDate ())); } Catch(ParseException e) {e.printstacktrace (); } //If you have already exceeded the set time, start at this time of the following day if(System.currenttimemillis () >starttime.gettime ()) StartTime=NewDate (Starttime.gettime () +Dayspan); //set the timer, starting with StartTime, to execute the task once every 5 secondsTimer.scheduleatfixedrate (Task, StartTime, 5*1000); } //tasks performed by the timer classTaskextendstimertask{@Override Public voidrun () {System.out.println ("Timed Program! "); } } }
How to execute a timed program on the server and execute the specified code at the specified time