-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhandler.go
57 lines (45 loc) · 1.11 KB
/
handler.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
package gotasks
import (
"log"
"reflect"
"runtime"
"sync"
)
type JobHandler func(ArgsMap) (ArgsMap, error)
type ReentrantOptions struct {
MaxTimes int
SleepyMS int
}
type ReentrantOption func(*ReentrantOptions)
func WithMaxTimes(max int) ReentrantOption {
return func(ro *ReentrantOptions) {
ro.MaxTimes = max
}
}
func WithSleepyMS(ms int) ReentrantOption {
return func(ro *ReentrantOptions) {
ro.SleepyMS = ms
}
}
var (
reentrantMap = map[string]ReentrantOptions{}
reentrantMapLock sync.RWMutex
)
func getHandlerName(handler JobHandler) string {
return runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
}
func Reentrant(handler JobHandler, options ...ReentrantOption) JobHandler {
handlerName := getHandlerName(handler)
reentrantMapLock.Lock()
defer reentrantMapLock.Unlock()
if _, ok := reentrantMap[handlerName]; ok {
log.Panicf("reentrant options of %s already exists!", handlerName)
return nil // never executed here
}
reentrantOptions := &ReentrantOptions{0, 0}
for _, o := range options {
o(reentrantOptions)
}
reentrantMap[handlerName] = *reentrantOptions
return handler
}