java的定时器

package com.bridata.dmp.system.user.timer;

import com.bridata.core.tool.utils.Func;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
/**
* Date: 2022/1/12:14:05 <br/>
* Description:定时计算当前用户在线时长
* @author gmx
*/
@Component
@Slf4j
public class OnLineTimer {

@Autowired
private RedisTemplate redisTemplate;

@Scheduled(cron = "0 0/1 * * * ? ")
public void countOnlineTime(){
//今日所有登陆用户
Set userIds = redisTemplate.boundSetOps("userIds").members();
for (Object userId:userIds) {
//所有在线时长
Long allTime = Func.toLong(redisTemplate.boundHashOps("allTime").get(userId));
//当前时间
long nowTime = System.currentTimeMillis();
//上一次登陆时间
long endTime = Func.toLong(redisTemplate.boundHashOps("endTime").get(userId));
long timeDiff = nowTime - endTime;
//当前时间到上次请求时间是否超过一分钟,若未超过,在线时间加一分钟
if (timeDiff < 60 * 1000) {
long newTime = allTime + 60 * 1000;
//将新增后在线时长放入reids
redisTemplate.boundHashOps("allTime").put(userId, newTime);
}
}
}
}


Cron - 在线Cron表达式生成器 (ciding.cc)


posted @ 2022-03-22 18:13  秃头小霸王  阅读(44)  评论(0)    收藏  举报