gitee.com/h79/goutils@v1.22.10/common/timer/expire.go (about)

     1  package timer
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  type Expire struct {
     8  	p        int   //精度
     9  	StartIn  int64 `json:"startIn"`
    10  	ExpireIn int64 `json:"expireIn"` //过期时间点
    11  }
    12  
    13  func NowExpireWithMillSecond(msec int64) Expire {
    14  	return NowMillExpireWithDuration(time.Millisecond * time.Duration(msec))
    15  }
    16  
    17  func NowExpireWithSecond(secondIn int64) Expire {
    18  	return NowExpireWithDuration(time.Second * time.Duration(secondIn))
    19  }
    20  
    21  func NowExpireWithMinute(minuteIn int64) Expire {
    22  	return NowExpireWithDuration(time.Minute * time.Duration(minuteIn))
    23  }
    24  
    25  func NowExpireWithHour(hourIn int64) Expire {
    26  	return NowExpireWithDuration(time.Hour * time.Duration(hourIn))
    27  }
    28  
    29  // NowExpireWithDuration 秒
    30  func NowExpireWithDuration(duration time.Duration) Expire {
    31  	now := time.Now()
    32  	expireIn := now.Add(duration).Unix()
    33  	return Expire{StartIn: now.Unix(), ExpireIn: expireIn}
    34  }
    35  
    36  // NowMillExpireWithDuration 豪秒
    37  func NowMillExpireWithDuration(duration time.Duration) Expire {
    38  	now := time.Now()
    39  	expireIn := now.Add(duration).UnixMilli()
    40  	return Expire{p: 1, StartIn: now.UnixMilli(), ExpireIn: expireIn}
    41  }
    42  
    43  func (e *Expire) IsExpired() bool {
    44  	return e.IsDiff(0)
    45  }
    46  
    47  func (e *Expire) IsDiff(diff int64) bool {
    48  	if e.ExpireIn == -1 { //永久不过期
    49  		return false
    50  	}
    51  	if e.p == 0 {
    52  		return time.Now().Unix()+diff >= e.ExpireIn
    53  	}
    54  	return time.Now().UnixMilli()+diff > e.ExpireIn
    55  }