[JAVA] servlet timed start and assumervlet start
Step 1:
Add the following code to web. xml:
<Load-on-startup> 10 </load-on-startup>.
<servlet> <servlet-name>AutoPayServlet</servlet-name> <servlet-class>autoE2E.AutoPayServlet</servlet-class> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping> <servlet-name>AutoPayServlet</servlet-name> <url-pattern>/AutoPayServlet</url-pattern> </servlet-mapping>
Step 2:
Core servlet code:
public static String autoPayRunTime; static Timer timer = null; static { timer = new Timer(); AutoUpdatePayStatu task = new AutoUpdatePayStatu(); timer.schedule(task, 1000); }
Step 3:
Logic code of the dao layer:
Package autoE2E; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. text. simpleDateFormat; import java. util. date; import java. util. timerTask; import util. JDBC_Connection; public class AutoUpdatePayStatu extends TimerTask {/*** get the order that has timed out on the current day for payment * @ return */@ Override public void run () {System. out. println ("-------- started querying -----"); try {} catch (Response t Ion e) {System. out. println ("An error occurred while querying the payment timeout order on the current day! "+ E);} finally {JDBC_Connection.release (resultSet, preparedStatement, connection);} AutoUpdatePayStatu task = new AutoUpdatePayStatu (); AutoPayServlet. timer. schedule (task, 10*60*1000); // loop once every 10 minutes }}
How to regularly start the service process in JAVA (high score for satisfactory answers)
1. while (true ){
If (the current time is ){
Do your Task ();
}
Thread. sleep (30*1000); // sleep 30 seconds
}
2. Write a. bat file (which calls your Java class) and run the. bat file at every day using Windows scheduled tasks.
3. Use the open-source Quartz framework to perform scheduled tasks. You may need to download the file, read the document, and write several configuration files.
The third and most professional type is recommended.
Java timer executes a method at every day
Calendar cal = Calendar. getInstance ();
// Execute the task at a specified point every day
Cal. set (Calendar. HOUR_OF_DAY, 12 );
Cal. set (Calendar. MINUTE, 0 );
Cal. set (Calendar. SECOND, 0 );
Timer timer = new Timer ();
Timer. schedule (new TimerTask (){
Public void run (){
// Executed content
}
}, Cal. getTime (), 24*60*60*1000 );