/
timer_task.go
54 lines (47 loc) · 865 Bytes
/
timer_task.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
package batchpipe
import (
"fmt"
"time"
"github.com/sirupsen/logrus"
)
type TimerTask struct {
started chan struct{}
finished chan struct{}
startTime time.Time
finishTime time.Time
}
func NewTimerTask() *TimerTask {
return &TimerTask{
started: make(chan struct{}),
finished: make(chan struct{}),
}
}
func (t *TimerTask) Start() {
select {
case <-t.started:
default:
close(t.started)
t.startTime = time.Now()
}
}
func (t *TimerTask) Finish() {
select {
case <-t.started:
select {
case <-t.finished:
default:
close(t.finished)
t.finishTime = time.Now()
}
default:
logrus.Warnln("Task not start yet")
}
}
func (t *TimerTask) CostTime() (time.Duration, error) {
select {
case <-t.finished:
return t.finishTime.Sub(t.startTime), nil
default:
return time.Duration(0), fmt.Errorf("Task not finished yet")
}
}