github.com/sandwich-go/boost@v1.3.29/xtime/timer.go (about) 1 package xtime 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 type Timer interface { 9 Cb() 10 stop() 11 GetDomain() string 12 } 13 14 type SafeTimer struct { 15 t *time.Timer 16 domain string 17 cb func() 18 } 19 20 func (t *SafeTimer) stop() { 21 t.t.Stop() 22 t.cb = nil 23 } 24 25 func (t *SafeTimer) Cb() { 26 defer func() { 27 t.cb = nil 28 }() 29 if t.cb != nil { 30 t.cb() 31 } 32 } 33 34 func (t *SafeTimer) GetDomain() string { 35 return t.domain 36 } 37 38 type DanglingTimer struct { 39 t *time.Timer 40 lock sync.RWMutex // 框架管理的timer不需要加锁,业务自己管理的timer需要加锁 41 domain string 42 cb func() 43 } 44 45 func (t *DanglingTimer) stop() { 46 t.Stop() 47 } 48 49 func (t *DanglingTimer) Stop() { 50 t.lock.Lock() 51 defer t.lock.Unlock() 52 t.t.Stop() 53 t.cb = nil 54 } 55 56 func (t *DanglingTimer) Reset(d time.Duration) bool { return t.t.Reset(d) } 57 58 func (t *DanglingTimer) Cb() { 59 t.lock.RLock() 60 cb := t.cb 61 t.lock.RUnlock() 62 if cb != nil { 63 cb() 64 } 65 } 66 67 func (t *DanglingTimer) GetDomain() string { 68 return t.domain 69 } 70 71 type Cron struct{ t Timer } 72 73 func (c *Cron) Stop() { 74 if c.t != nil { 75 c.t.stop() 76 } 77 }