forked from LiuPai/himawari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
77 lines (68 loc) · 1.18 KB
/
worker.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
67
68
69
70
71
72
73
74
75
76
77
package himawari
import (
"log"
"sync"
"time"
)
type Work interface {
Name() string
Do() error
MaxFailTimes() int
}
type Worker struct {
work Work
TriedTimes int
Done bool
manager *Manager
}
func NewWorker(work Work, manager *Manager) *Worker {
return &Worker{
work: work,
manager: manager,
}
}
func (w *Worker) Work() {
for {
if w.TriedTimes >= w.work.MaxFailTimes() {
w.Done = false
break
}
start := time.Now()
err := w.work.Do()
dur := time.Since(start)
if err == nil {
log.Printf("[%s] tried: %d use: %v done",
w.work.Name(), w.TriedTimes, dur)
w.Done = true
break
}
log.Printf("[%s] tried: %d use: %v err: %v",
w.work.Name(), w.TriedTimes, dur, err)
w.TriedTimes++
}
w.manager.wg.Done()
}
type Manager struct {
workers []*Worker
wg *sync.WaitGroup
}
func NewManager() *Manager {
return &Manager{
wg: &sync.WaitGroup{},
}
}
func (m *Manager) NewWork(work Work) {
worker := NewWorker(work, m)
m.workers = append(m.workers, worker)
m.wg.Add(1)
go worker.Work()
}
func (m *Manager) Done() bool {
m.wg.Wait()
for _, worker := range m.workers {
if !worker.Done {
return false
}
}
return true
}