java web program to implement a listener, the timing of the implementation of a business:
1. write listener.
2. Configure a listener in web.xml, the listener can set the number of initialization parameters, according to business needs.
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 configure the program:
<listener>
<listener-class>SendParamListener</listener-class>
</listener>
You can
be set before listener some initialization parameters:
<context-param>
<param-name>参数名</param-name>
<param-value>参数值</param-value>
</context-param>
Is then
used in the program initialization process:
event.getServletContext().getInitParameter("参数名");
To
obtain the parameter values related to handle their own business