com.infusers.core.stats.users.ActiveUserService Maven / Gradle / Ivy
package com.infusers.core.stats.users;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.infusers.core.logger.ILogger;
@Service
@EnableScheduling
public class ActiveUserService {
private ILogger log = new ILogger(ActiveUserService.class);
private static final String CLASS_NAME = "ActiveUserService";
@Autowired
private ApplicationEventPublisher eventPublisher;
private final Map activeUsers = new ConcurrentHashMap<>();
// Method to update the user's activity timestamp
public void updateUserActivity(String userName) {
log.debug(CLASS_NAME + ".updateUserActivity()--> userName = " + userName);
activeUsers.put(userName, Instant.now());
publishActiveUsersCount();
}
public void logout(String userName) {
activeUsers.remove(userName);
publishActiveUsersCount();
}
// Scheduled task to clean up inactive users
@Scheduled(fixedRate = 60000) // Runs every 60 seconds
public void cleanupInactiveUsers() {
log.debug(CLASS_NAME + ".cleanupInactiveUsers()--> Started : "+activeUsers.size());
Instant now = Instant.now();
activeUsers.entrySet().removeIf(entry ->
ChronoUnit.MINUTES.between(entry.getValue(), now) > 15 // 15 minutes of inactivity
);
log.debug(CLASS_NAME + ".cleanupInactiveUsers()--> Ended : "+activeUsers.size());
publishActiveUsersCount();
}
// Method to get the number of active users
public int getActiveUserCount() {
return activeUsers.size();
}
private void publishActiveUsersCount() {
long count = getActiveUserCount();
log.debug(CLASS_NAME + ".publishActiveUsersCount()--> count = " + count);
eventPublisher.publishEvent(new ActiveUserCountEvent(this, count));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy