java web监听程序

java web程序中实现一个监听程序, 定时执行某项业务:

1. 写好监听程序.

2.  在web.xml中配置一个listener,这个listener中可以设置一些初始化参数, 根据业务需要.

监听程序:

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

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

import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 监听程序
 * @author yangx
 *
 */
public class SendParamListener implements ServletContextListener {
	private SendErrorService sendErrorService;
	
	private ParamThread paramThread;
	
	class ParamThread extends TimerTask {
		private boolean isStop = false;
		
		@Override
		public void run() {
			if (!isStop) {
				// 这里处理自己的业务
				System.out.println("线程执行...");
			}
		}
		
		public void stopThread(){
			isStop = true;
		}
	}

	public void contextInitialized(ServletContextEvent event) {
		//ServletContext sc = event.getServletContext();
		//sendErrorService = (SendErrorService) WebApplicationContextUtils.getWebApplicationContext(sc).getBean("sendErrorService");
		paramThread = new ParamThread();
		Timer timer = new Timer();
		timer.schedule(paramThread, 1000, Constants.getPARAM_SEND_DATE()*1000);
	}
	
	public void contextDestroyed(ServletContextEvent event) {
		paramThread.stopThread();
	}
}

web.xml中配置程序:

<listener>
		<listener-class>SendParamListener</listener-class>
	</listener>
可以 在listener之前设置一些初始化参数:

<context-param>
		<param-name>参数名</param-name>
		<param-value>参数值</param-value>
	</context-param>
然后 在程序初始化方法中使用:

event.getServletContext().getInitParameter("参数名");
获取参数值处理自己的相关业务
发布了90 篇原创文章 · 获赞 21 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/yx13649017813/article/details/41820941
今日推荐