import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
public class OnLineUserDoTimer {
private ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
public void executeTimer( final ServletContext application) {
Runnable task = new Runnable() {
public void run() {
removeUser(application); //调用操作实现方法
}
};
if (scheduler.isShutdown()) {
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 0, 60, TimeUnit.SECONDS);
} else {
scheduler.scheduleAtFixedRate(task, 0, 60, TimeUnit.SECONDS); // 延迟0,每隔60行一次
}
}
//停止任务,不再提交新任务,已提交任务会继续执行以致完成
public void stop() {
scheduler.shutdown();
}
//删除时间间隔超过指定值的用户记录
public void removeUser(ServletContext application){
Object o=application.getAttribute("OnLineUserList");
if(o!=null){
Map onLineUserList=(HashMap)o;
Set keys=onLineUserList.keySet();
Iterator lt=keys.iterator();
while(lt.hasNext()){
Object key=lt.next();
OnLineUser user=(OnLineUser)onLineUserList.get(key);
Date lasttime=user.getLastreqTime();
Date now=new Date();
int fz=(int)((now.getTime()-lasttime.getTime())/(1000*60));
if(fz>1){
onLineUserList.remove(key);
}
}
}
}
}