forked from YoungPioneers/blog4go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeCache.go
100 lines (84 loc) · 2.13 KB
/
timeCache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright (c) 2015, huangjunwei <[email protected]>. All rights reserved.
package blog4go
import (
"sync"
"time"
)
const (
// PrefixTimeFormat const time format prefix
PrefixTimeFormat = "[2006/01/02:15:04:05]"
// DateFormat date format
DateFormat = "2006-01-02"
)
// timeFormatCacheType is a time formated cache
type timeFormatCacheType struct {
// current time
now time.Time
// current date
date string
// current formated date
format []byte
// yesterdate
dateYesterday string
// lock for read && write
lock *sync.RWMutex
}
// global time cache instance used for every log writer
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)
// update timeCache every seconds
go func() {
// tick every seconds
t := time.Tick(1 * time.Second)
//UpdateTimeCacheLoop:
for {
select {
case <-t:
timeCache.fresh()
}
}
}()
}
// Now now
func (timeCache *timeFormatCacheType) Now() time.Time {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.now
}
// Date date
func (timeCache *timeFormatCacheType) Date() string {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.date
}
// DateYesterday date
func (timeCache *timeFormatCacheType) DateYesterday() string {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.dateYesterday
}
// Format format
func (timeCache *timeFormatCacheType) Format() []byte {
timeCache.lock.RLock()
defer timeCache.lock.RUnlock()
return timeCache.format
}
// fresh data in timeCache
func (timeCache *timeFormatCacheType) fresh() {
timeCache.lock.Lock()
defer timeCache.lock.Unlock()
// get current time and update 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)
}
}