1、在web.xml里面配置一个listener
<listener>
<listener-class>com.xxxListener</listener-class>
</listener>
2、配置监听类
public class xxxListener implements ServletContextListener {
private Timer timer = null;
//半个小时执行一次
private static long L_EXE_TIME = 30*60*1000L;
public void contextDestroyed(ServletContextEvent arg0) {
log.info("*************** ***************************");
if(timer!=null){
timer.cancel();
}
}
public void contextInitialized(ServletContextEvent arg0) {
startExchangeTask(L_EXE_TIME);
}
/**
* 循环执行任务
* @param myTask 要执行的任务
* @param dayInterval 每隔多少天执行一次任务
* @param hour 每隔多少天在几点执行任务
* @param minute 每隔多少天在几点几分执行任务
* @author linshutao
* */
public void startExchangeTask(long dayInterval){
if(timer==null){
timer = new Timer(true);
}
timer.schedule(new XxxTools(), 0, dayInterval);
}
}
3、实施工具类
public class XxxTools extends TimerTask {
private static Log log = LogFactory.getLog(JTTAptExchangeTools.class);
private static String SYS_CODE ="0000";
private static String SYS_AUTH_CERT ="zc0000";
public XxxTools() {
super();
}
@Override
public void run() {
log.info("#################################################################");
log.info(" start * 统一受理平台交换服务。。。 ");
log.info("*************** *************************************************");
Date bD= new Date();
dataExchange();
Date eD= new Date();
log.info(" 本次数据交换执行时间为: "+((eD.getTime()-bD.getTime())/1000)+"秒");
}
4、出现这种情况主要是在tomcat 里面的配置service.xml
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<Context path="" reloadable="false" docBase="E:\apache-tomcat-7.0.35\webapps\project" />
</Host>
主要这个地方添加了
<Context path="" reloadable="false" docBase="E:\apache-tomcat-7.0.35\webapps\project" />
就会出现每次run()方法执行两次,解决方法就是appBase="webapps"设置为空appBase="" 就好了。