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);
}
}
}
}
}

本文介绍了一个用于定期清理长时间未活动在线用户的Java实现方案。通过使用ScheduledExecutorService来调度任务,每60秒检查一次在线用户列表,并移除最后请求时间超过两分钟的用户。该方法适用于Web应用中维护活跃用户列表。

4594

被折叠的 条评论
为什么被折叠?



