-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeoutmap.go
51 lines (44 loc) · 884 Bytes
/
timeoutmap.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
package main
import "time"
type timeoutmapdata struct {
timeout time.Time
data interface{}
}
type TimeOutMap struct {
data map[string]*timeoutmapdata
timeout time.Duration
ticker *time.Ticker
}
func NewTimeOutMap(dt time.Duration) *TimeOutMap {
return &TimeOutMap{
data: make(map[string]*timeoutmapdata),
timeout: dt,
ticker: time.NewTicker(dt),
}
}
func (tom *TimeOutMap) Start() {
go func() {
for {
<-tom.ticker.C
now := time.Now()
for k, v := range tom.data {
if now.Sub(v.timeout) > tom.timeout {
delete(tom.data, k)
}
}
}
}()
}
func (tom *TimeOutMap) Set(k string, v interface{}) {
tom.data[k] = &timeoutmapdata{
timeout: time.Now(),
data: v,
}
}
func (tom *TimeOutMap) Get(k string) (interface{}, bool) {
if v, ok := tom.data[k]; ok {
v.timeout = time.Now()
return v.data, true
}
return nil, false
}