forked from ksckaan1/gokachu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoll.go
More file actions
40 lines (30 loc) · 850 Bytes
/
poll.go
File metadata and controls
40 lines (30 loc) · 850 Bytes
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
package gokachu
import "time"
// poll deletes expired values from the cache with the given poll interval. If context is cancelled, the polling stops.
func (g *Gokachu[K, V]) poll() {
ticker := time.NewTicker(g.pollInterval)
defer ticker.Stop()
for {
select {
case <-g.pollCancel: // when Close method called, polling stops
g.pollCancel = nil
g.wg.Done()
return
case <-ticker.C:
g.mut.Lock()
now := time.Now()
for key := range g.store {
elem := g.store[key]
// elem must be non-expired
if elem.Value.(*valueWithTTL[K, V]).expireTime.IsZero() || elem.Value.(*valueWithTTL[K, V]).expireTime.After(now) {
continue
}
// delete expired element
g.runOnDeleteHooks(key, elem.Value.(*valueWithTTL[K, V]).value)
g.elems.Remove(elem)
delete(g.store, key)
}
g.mut.Unlock()
}
}
}