forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
periodic.go
79 lines (63 loc) · 1.32 KB
/
periodic.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
78
79
package task
import (
"sync"
"time"
)
// Periodic is a task that runs periodically.
type Periodic struct {
// Interval of the task being run
Interval time.Duration
// Execute is the task function
Execute func() error
// OnFailure will be called when Execute returns non-nil error
OnError func(error)
access sync.RWMutex
timer *time.Timer
closed bool
}
func (t *Periodic) setClosed(f bool) {
t.access.Lock()
t.closed = f
t.access.Unlock()
}
func (t *Periodic) hasClosed() bool {
t.access.RLock()
defer t.access.RUnlock()
return t.closed
}
func (t *Periodic) checkedExecute() error {
if t.hasClosed() {
return nil
}
if err := t.Execute(); err != nil {
return err
}
t.access.Lock()
t.timer = time.AfterFunc(t.Interval, func() {
if err := t.checkedExecute(); err != nil && t.OnError != nil {
t.OnError(err)
}
})
t.access.Unlock()
return nil
}
// Start implements common.Runnable. Start must not be called multiple times without Close being called.
func (t *Periodic) Start() error {
t.setClosed(false)
if err := t.checkedExecute(); err != nil {
t.setClosed(true)
return err
}
return nil
}
// Close implements common.Closable.
func (t *Periodic) Close() error {
t.access.Lock()
defer t.access.Unlock()
t.closed = true
if t.timer != nil {
t.timer.Stop()
t.timer = nil
}
return nil
}