github.com/DerekStrickland/consul@v1.4.5/agent/consul/session_timers.go (about) 1 package consul 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 // SessionTimers provides a map of named timers which 9 // is safe for concurrent use. 10 type SessionTimers struct { 11 sync.RWMutex 12 m map[string]*time.Timer 13 } 14 15 func NewSessionTimers() *SessionTimers { 16 return &SessionTimers{m: make(map[string]*time.Timer)} 17 } 18 19 // Get returns the timer with the given id or nil. 20 func (t *SessionTimers) Get(id string) *time.Timer { 21 t.RLock() 22 defer t.RUnlock() 23 return t.m[id] 24 } 25 26 // Set stores the timer under given id. If tm is nil the timer 27 // with the given id is removed. 28 func (t *SessionTimers) Set(id string, tm *time.Timer) { 29 t.Lock() 30 defer t.Unlock() 31 if tm == nil { 32 delete(t.m, id) 33 } else { 34 t.m[id] = tm 35 } 36 } 37 38 // Del removes the timer with the given id. 39 func (t *SessionTimers) Del(id string) { 40 t.Set(id, nil) 41 } 42 43 // Len returns the number of registered timers. 44 func (t *SessionTimers) Len() int { 45 t.RLock() 46 defer t.RUnlock() 47 return len(t.m) 48 } 49 50 // ResetOrCreate sets the ttl of the timer with the given id or creates a new 51 // one if it does not exist. 52 func (t *SessionTimers) ResetOrCreate(id string, ttl time.Duration, afterFunc func()) { 53 t.Lock() 54 defer t.Unlock() 55 56 if tm := t.m[id]; tm != nil { 57 tm.Reset(ttl) 58 return 59 } 60 t.m[id] = time.AfterFunc(ttl, afterFunc) 61 } 62 63 // Stop stops the timer with the given id and removes it. 64 func (t *SessionTimers) Stop(id string) { 65 t.Lock() 66 defer t.Unlock() 67 if tm := t.m[id]; tm != nil { 68 tm.Stop() 69 delete(t.m, id) 70 } 71 } 72 73 // StopAll stops and removes all registered timers. 74 func (t *SessionTimers) StopAll() { 75 t.Lock() 76 defer t.Unlock() 77 for _, tm := range t.m { 78 tm.Stop() 79 } 80 t.m = make(map[string]*time.Timer) 81 }