• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

timeCache.go

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
package blog4go

import (
"sync"
"time"
)

const (
// PrefixTimeFormat  时间格式前缀
PrefixTimeFormat = "[2006/01/02:15:04:05]"

// DateFormat 时间格式
DateFormat = "2006-01-02"
)

// timeFormatCacheType是一个时间格式的缓存
type timeFormatCacheType struct {
//当前时间
now time.Time
//当前时间格式
date string
//当前格式化的时间
format []byte
//昨天
dateYesterday string
//读写锁
lock *sync.RWMutex
}

//全局时间的缓存  对于写日志
var timeCache = timeFormatCacheType{}

func init() {
timeCache.lock = new(sync.RWMutex)  //初始化锁
timeCache.now = time.Now() //当前时间
timeCache.date = timeCache.now.Format(DateFormat)  //当前时间的格式化
timeCache.format = []byte(timeCache.now.Format(PrefixTimeFormat)) //当前时间格式化转为字节数组
timeCache.dateYesterday = timeCache.now.Add(-24 * time.Hour).Format(DateFormat) // 获取当前时间的昨天

//每秒跟新一下timeCache 中的时间  当独开启一个协成
go func() {
// tick 创建一个跟新时间周期
t := time.Tick(1 * time.Second)

//UpdateTimeCache  Loop:
for {
select {
case <-t:
timeCache.fresh()
}
}
}()
}

//获取当前时间
func (timeCache *timeFormatCacheType) Now() time.Time {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.now
}

//获取当前时间
func (timeCache *timeFormatCacheType) Date() string {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.date
}

//获取昨天时间
func (timeCache *timeFormatCacheType) DateYesterday() string {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.dateYesterday
}

//当前时间格式化函数
func (timeCache *timeFormatCacheType) Format() []byte {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.format
}

// 刷新 timeCache的时间
func (timeCache *timeFormatCacheType) fresh() {
timeCache.lock.Lock()
defer timeCache.lock.Unlock()

// get current time and update timeCache
       //获取当期时间  并且更新timeCache  缓存时间
now := time.Now()
timeCache.now = now
timeCache.format = []byte(now.Format(PrefixTimeFormat))
date := now.Format(DateFormat)
if date != timeCache.date {
timeCache.dateYesterday = timeCache.date
timeCache.date = now.Format(DateFormat)
}
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
linux-关机出现TellingINITtogotosingleusermode.无法关机发布时间:2022-07-10
下一篇:
5个理由让你选择Go,抛弃Python发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap