This article describes the Java Web implementation method to add timing tasks. Share it for your reference, as follows:
Timed task time control category
/** * Timed 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 00:00 ***/ calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date date = calendar.getTime(); //Time to execute the timing task// When starting the server, if the time to execute the timing task for the first time is less than the current time task, it will be executed immediately. // Therefore, in order to prevent the restart of the server from causing repeated execution of tasks, it is necessary to modify the time to execute the timing task 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(); }}Timed task operation subject category
/** * Timed task operation body* * @author liming * */public class DailyDataTimerTask extends TimerTask { private static Logger log = Logger.getLogger(DailyDataTimerTask.class); @Override public void run() { try { //Write the content you want to execute here System.out.println("come in DailyDataTimerTask"); } catch (Exception e) { log.info("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Timed task listener
/** * Timed task listener* * @author liming * */public class DailyDataTaskListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { new TimerManager(); } public void contextDestroyed(ServletContextEvent event) { }}web.xml add listener
<!--Load daily data update timing task file--><listener> <listener-class> com.honsto.web.job.DailyDataTaskListener </listener-class></listener>
For more information about Java related content, please check out the topics of this site: "Java Data Structure and Algorithm Tutorial", "Summary of Java File and Directory Operation Skills", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.