-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
74 lines (61 loc) · 1.17 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
package workerpool
import "time"
type Worker struct {
id int
workedJobs int
runningJobId string
busiedAt *time.Time
idledAt *time.Time
}
func NewWorker(id int) *Worker {
now := time.Now().UTC()
return &Worker{
id: id,
idledAt: &now,
}
}
func (w *Worker) Run(job Job) {
w.beforeJob(job)
job.Exec()
w.afterJob()
}
func (w *Worker) beforeJob(job Job) {
now := time.Now().UTC()
w.busiedAt = &now
w.idledAt = nil
w.workedJobs++
w.runningJobId = job.Id()
}
func (w *Worker) afterJob() {
w.busiedAt = nil
now := time.Now().UTC()
w.idledAt = &now
w.runningJobId = ""
}
func (w Worker) Id() int {
return w.id
}
func (w Worker) BusiedAt() *time.Time {
return w.busiedAt
}
func (w Worker) BusiedDuration() time.Duration {
if w.busiedAt == nil {
return time.Duration(0)
}
return time.Now().UTC().Sub(*w.busiedAt)
}
func (w Worker) IdledAt() *time.Time {
return w.idledAt
}
func (w Worker) IdledDuration() time.Duration {
if w.idledAt == nil {
return time.Duration(0)
}
return time.Now().UTC().Sub(*w.idledAt)
}
func (w Worker) RunningJobId() string {
return w.runningJobId
}
func (w Worker) WorkedJobs() int {
return w.workedJobs
}