1, the class of timed execution
Package Com.utils;import java.io.ioexception;import java.text.simpledateformat;import java.util.Date;
Public classMyTimer extends Thread {//interval time: Hours Private intintervalhours; //error (time required for operation may cause error): minutes Private intDeviationminute; //Execution Time PrivateString RunTime; PublicMyTimer () {//parameter AcquisitionIntervalhours = -; Deviationminute=5; RunTime="19:30"; } Public voidrun () { while(! This. isinterrupted ()) {//thread does not interrupt execution loop//get current time: hh:mmDate now =NewDate (); SimpleDateFormat DateFormat=NewSimpleDateFormat ("hh:mm"); String hours=Dateformat.format (now); //Time arrives if(Hours.equals (runTime)) {Dorun (); Try { //long-time sleep: Interval time-ErrorThread.Sleep (Intervalhours *3600* +-Deviationminute * -* +); } Catch(interruptedexception e) {e.printstacktrace (); } }Else{ Try { //wait interval: 30sThread.Sleep (30000); System. out. println (hours); } Catch(interruptedexception e) {e.printstacktrace (); } } } } /** * Processing*/ Private voidDorun () {}}
2,servlet
Packagecom.utils;ImportJavax.servlet.http.HttpServlet; Public classMyservletextendshttpservlet{/** * */ Private Static Final LongSerialversionuid = 1L; PrivateMyTimer MyTimer; PublicMyservlet () {} Public voidinit () {String str=NULL; if(str = =NULL&& mytimer==NULL) {MyTimer=NewMyTimer (); Mytimer.start (); }
super.init (); } Public voiddestory () {if(mytimer!=NULL&&mytimer.isinterrupted ()) {Mytimer.interrupt (); }
Super.destroy (); } }
3,web.xml
<servlet> <Servlet-name>Myservlet</Servlet-name> <Servlet-class>Com.utils.MyServlet</Servlet-class> <Load-on-startup>9</Load-on-startup
</servlet>
Httpservlet,java Web Backend Service