-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwork.go
66 lines (55 loc) · 1.36 KB
/
work.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
60
61
62
63
64
65
66
package job
import (
"context"
"time"
"golang.org/x/time/rate"
)
type ReportError interface {
Report(ctx context.Context, worker, content string) error
}
type Worker struct {
name string
job Handler
limiter *rate.Limiter
reStartLimiter *rate.Limiter
reportError ReportError
sleep time.Duration
}
type Handler func(ctx context.Context) error
type WorkerOption func(worker *Worker)
func WithReport(report ReportError) WorkerOption {
return func(worker *Worker) {
worker.reportError = report
}
}
func WithSleep(duration time.Duration) WorkerOption {
return func(worker *Worker) {
worker.sleep = duration
}
}
func WithLimiter(limiter *rate.Limiter) WorkerOption {
return func(worker *Worker) {
worker.limiter = limiter
}
}
func WithLimiterDuration(duration time.Duration) WorkerOption {
return func(worker *Worker) {
worker.limiter = rate.NewLimiter(rate.Every(duration), 1)
}
}
func NewWorker(name string, job Handler, opts ...WorkerOption) *Worker {
w := &Worker{
name: name,
job: job,
// 默认每分钟执行1次任务
limiter: rate.NewLimiter(rate.Every(time.Minute), 1),
// 默认每小时最多重启5次任务
reStartLimiter: rate.NewLimiter(rate.Every(time.Hour), 5),
// 限流不通过时的休眠时间,默认为 1s
sleep: time.Second,
}
for _, opt := range opts {
opt(w)
}
return w
}