JAVA线程定时器(web)

时间:2021-02-21 16:47:36

在J2EE中,web应用总有定时更新数据或者缓存的时候,除了spring中用的 
quartz 外还有线程方式,可能很少被关注. 

package com.dtserver.client.listener;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;/**DTServer各种线程与定时任务的启动 */public class ServerSocketListener implements ServletContextListener {//定时private Timer timer;//在服务器启动时,启动服务器线程。try {interval = Integer.valueOf(XmlUtil.getScanDtDataInterval()) * 60000;//三分钟一次//interval = 30000;} catch (Exception exception) {interval = 3 * 60000;}timer.schedule(new SendData(), 0, interval);}}
被调用的类

package com.dtserver.client.logic;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.TimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SendData extends TimerTask {

private static final Log log = LogFactory.getLog(SendData.class);

private static final String ASURA_FILE_NAME = "/config/webservice_url.properties";

private final static Properties props;

static {
props = new Properties();
try {
props.load(WebFrameAction.class
.getResourceAsStream(XXX));
} catch (IOException e) {
throw new RuntimeException("can't load systemconfig.properties", e);
}
}

@SuppressWarnings("unchecked")
@Override
public void run() {

log.info("开始上传的时间" + new Date());


}


}



web.xml

要想在web项目中启动必须在这里配入口.

<!--服务器启动时,启动服务器线程-->
<listener>
<description>Socket服务器线程随服务器启动而启动</description>
<listener-class>com.dtserver.client.listener.ServerSocketListener</listener-class>
</listener>

看效果去