-
Notifications
You must be signed in to change notification settings - Fork 5
/
helper_closer.go
59 lines (53 loc) · 1.08 KB
/
helper_closer.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
package t
import (
"fmt"
"log"
"sync"
"time"
)
var defaultRecover = func(err error) {
log.Println("panic err catch:", err)
}
func SetDefaultRecover(dr func(err error)) {
defaultRecover = dr
}
func WithRecover(h func(), errDefaultRecover ...func(err error)) {
defer func() {
if err := recover(); err != nil {
if len(errDefaultRecover) > 0 {
errDefaultRecover[0](fmt.Errorf("%v", err))
} else {
defaultRecover(fmt.Errorf("%v", err))
}
}
}()
h()
}
func WithMutexContext(mu *sync.Mutex, fn func()) {
mu.Lock()
defer mu.Unlock()
fn()
}
func WithRWMutexContext(mur *sync.RWMutex, fn func()) {
mur.RLock()
defer mur.RUnlock()
fn()
}
func WithTicker(duration time.Duration, fn func()) {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for {
select {
case <-ticker.C:
fn()
}
}
}
func WithRunTimeContext(closer func(), callback func(time.Duration)) {
// 记录开始时间
start := time.Now()
closer()
timeduration := time.Since(start)
//log.Println("执行完毕,用时:", timeduration.Seconds(),timeduration.Seconds()>1.1)
callback(timeduration)
}