-
Notifications
You must be signed in to change notification settings - Fork 39
/
timer.go
90 lines (71 loc) · 1.38 KB
/
timer.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
80
81
82
83
84
85
86
87
88
89
90
// (c) Copyright IBM Corp. 2021
// (c) Copyright Instana Inc. 2020
package internal
import (
"sync"
"time"
"github.com/instana/go-sensor/autoprofile/internal/logger"
)
// Timer periodically executes provided job after a delay until it's stopped. Any panic
// occurred inside the job is recovered and logged
type Timer struct {
mu sync.Mutex
delayTimer *time.Timer
done chan bool
stopped bool
ticker *time.Ticker
}
// NewTimer initializes a new Timer
func NewTimer(delay, interval time.Duration, job func()) *Timer {
t := &Timer{
done: make(chan bool),
}
t.delayTimer = time.AfterFunc(delay, func() {
defer recoverAndLog()
if interval > 0 {
t.runTicker(interval, job)
}
if delay > 0 {
job()
}
})
return t
}
func (t *Timer) runTicker(interval time.Duration, job func()) {
t.mu.Lock()
defer t.mu.Unlock()
if t.stopped {
return
}
t.ticker = time.NewTicker(interval)
go func() {
defer recoverAndLog()
for {
select {
case <-t.ticker.C:
job()
case <-t.done:
return
}
}
}()
}
// Stop stops the job execution
func (t *Timer) Stop() {
if t.stopped {
return
}
t.mu.Lock()
defer t.mu.Unlock()
t.stopped = true
t.delayTimer.Stop()
close(t.done)
if t.ticker != nil {
t.ticker.Stop()
}
}
func recoverAndLog() {
if err := recover(); err != nil {
logger.Error("recovered from panic in agent:", err)
}
}