TimeUnit的使用
-
简介
TimeUnit是java.util.concurrent包中一个类表示给定单元粒度的时间段;
主要作用为 ①时间颗粒度转换②延时;常在redis set保存数据设置失效时间使用; -
颗粒度
TimeUnit.DAYS //天
TimeUnit.HOURS //小时
TimeUnit.MINUTES //分钟
TimeUnit.SECONDS //秒
TimeUnit.MILLISECONDS //毫秒
TimeUnit.NANOSECONDS //毫微秒
TimeUnit.MICROSECONDS //微秒
- 颗粒转换
public long toMillis(long d) //转化成毫秒
public long toSeconds(long d) //转化成秒
public long toMinutes(long d) //转化成分钟
public long toHours(long d) //转化成小时
public long toDays(long d) //转化天
- 延时
//常用方法
Thread.sleep( 10* 1000 );
System.out.println( "延时10s");
TimeUnit.MINUTES.sleep( 2 );
System.out.println( "延时2分钟");
例子:
方法:
public void set(String key, Object value, long time, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, time, timeUnit);
}
使用:
redisUtil.set(RedisKeyConstants.LOGIN_VALIDATE_KEY + key, verifyCode[0], 2L, TimeUnit.MINUTES);