servlet监听器 定时执行***

web.xml
        <listener>
		<listener-class>TaskListener</listener-class>
	</listener>


TaskListener.java


import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class TaskListener implements ServletContextListener {

	private static final Logger logger = Logger
			.getLogger(TaskListener.class);

	private static Timer timer;

	private static UpdateProbationTask probationTask = new UpdateProbationTask();

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {

		if (timer != null) {
			timer.cancel();
			logger.debug("Timer Canceled");
		}
		logger.debug("web container contextDestroyed");
	}
 
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent arg0) {

		try {
			
			timer = new Timer(true);
			GregorianCalendar now = new GregorianCalendar();
			//每天2点执行
			now.set(Calendar.HOUR_OF_DAY, 2);
			now.set(Calendar.MINUTE, 0);
			now.set(Calendar.SECOND, 0);
			timer.schedule(probationTask, now.getTime());  
  
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Unable to initialize Schedule.");  
		}
		logger.debug("web container contextInitialized");

	}
}



UpdateProbationTask.java


import java.sql.SQLException;
import java.util.TimerTask;

public class UpdateProbationTask extends TimerTask {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println("#$#^%$%^$%^&#$%#$%");
		} catch (Exception e1) {
			// TODO 自动生成 catch 块
			e1.printStackTrace();
		}
	}

}


你可能感兴趣的:(java,sql,log4j,Web,servlet)