1. 程式人生 > 其它 >java的定時器

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)