Java Web implementation method example for adding scheduled tasks, Java Web implementation example
This example describes how to add scheduled tasks in Java Web. We will share this with you for your reference. The details are as follows:
Scheduled task time control
/*** Scheduled task time control ** @ author liming **/public class TimerManager {// time interval private static final long PERIOD_DAY = 24*60*60*1000; public TimerManager () {Calendar calendar = Calendar. getInstance ();/*** customize the daily execution method at ***/calendar. set (Calendar. HOUR_OF_DAY, 0); calendar. set (Calendar. MINUTE, 0); calendar. set (Calendar. SECOND, 0); Date date = calendar. getTime (); // The time when the scheduled task is executed // If the scheduled task is executed for the first time when the server is started Tasks that are earlier than the current time will be executed immediately. // To prevent repeated tasks from being executed due to server restart, you need to change the scheduled task execution time to the next day. If (date. before (new Date () {date = this. addDay (date, 1);} Timer timer = new Timer (); DailyDataTimerTask task = new DailyDataTimerTask (); // task execution interval. Timer. schedule (task, date, PERIOD_DAY);} // increase or decrease the number of days public Date addDay (Date date, int num) {Calendar startDT = Calendar. getInstance (); startDT. setTime (date); startDT. add (Calendar. DAY_OF_MONTH, num); return startDT. getTime ();}}
Scheduled task operation subject
/*** Scheduled task operator ** @ author liming **/public class DailyDataTimerTask extends TimerTask {private static Logger log = Logger. getLogger (DailyDataTimerTask. class); @ Override public void run () {try {// here write the content you want to execute System. out. println ("come in DailyDataTimerTask");} catch (Exception e) {log.info ("------------- parsing information Exception --------------");}}}
Scheduled task listener
/*** Scheduled task listener ** @ author liming **/public class DailyDataTaskListener implements ServletContextListener {public void contextInitialized (ServletContextEvent event) {new TimerManager ();} public void contextDestroyed (ServletContextEvent event ){}}
Add listeners in web. xml
<! -- Load the daily data update task file --> <listener-class> com. honsto. web. job. DailyDataTaskListener </listener-class> </listener>