1
- package raterunner
1
+ package raterun
2
2
3
3
import (
4
4
"errors"
@@ -13,13 +13,22 @@ type Rate struct {
13
13
Rate time.Duration // run in amount of Duration
14
14
}
15
15
16
+ type Runner interface {
17
+ // Terminate cancels scheduling for the next run
18
+ Terminate ()
19
+ // RestartRate resets function calling back to first defined rate
20
+ RestartRate ()
21
+ // run starts running the function at rates provided to the constructor
22
+ Run ()
23
+ }
24
+
16
25
// New creates a new runner which varies in time according to given rates
17
- func New (fn RunFunction , rates []Rate ) (* RateRunner , error ) {
26
+ func New (fn RunFunction , rates []Rate ) (* rrInstance , error ) {
18
27
if len (rates ) == 0 {
19
28
return nil , errors .New ("empty rates" )
20
29
}
21
30
22
- rateRunner := & RateRunner {
31
+ rateRunner := & rrInstance {
23
32
terminateRunner : make (chan bool , 1 ),
24
33
restartRates : make (chan bool , 1 ),
25
34
runFunction : fn ,
@@ -30,7 +39,7 @@ func New(fn RunFunction, rates []Rate) (*RateRunner, error) {
30
39
return rateRunner , nil
31
40
}
32
41
33
- type RateRunner struct {
42
+ type rrInstance struct {
34
43
terminateRunner chan bool
35
44
restartRates chan bool
36
45
// function that is going to be run at specific timed intervals, according to current rate set at a specific moment in time
@@ -44,18 +53,15 @@ type RateRunner struct {
44
53
rateTimer * time.Timer
45
54
}
46
55
47
- // Terminate finishes the runner
48
- func (rr * RateRunner ) Terminate () {
56
+ func (rr * rrInstance ) Terminate () {
49
57
rr .terminateRunner <- true
50
58
}
51
59
52
- // RestartRate resets function calling back to first defined rate
53
- func (rr * RateRunner ) RestartRate () {
60
+ func (rr * rrInstance ) RestartRate () {
54
61
rr .restartRates <- true
55
62
}
56
63
57
- // run starts running the function following the rates given to the constructor
58
- func (rr * RateRunner ) Run () {
64
+ func (rr * rrInstance ) Run () {
59
65
go func () {
60
66
rr .rateTimer = time .NewTimer (rr .rates [0 ].Start )
61
67
rr .fnTicker = time .NewTicker (time .Hour )
@@ -80,7 +86,7 @@ func (rr *RateRunner) Run() {
80
86
}()
81
87
}
82
88
83
- func (rr * RateRunner ) scheduleNextRate (rateIndex int ) {
89
+ func (rr * rrInstance ) scheduleNextRate (rateIndex int ) {
84
90
if rateIndex < len (rr .rates ) {
85
91
nextRate := rr .rates [rateIndex ]
86
92
// close rateTimer if it hasn't run yet to prevent double runs
@@ -89,7 +95,7 @@ func (rr *RateRunner) scheduleNextRate(rateIndex int) {
89
95
}
90
96
}
91
97
92
- func (rr * RateRunner ) runAtRate (rate Rate ) {
98
+ func (rr * rrInstance ) runAtRate (rate Rate ) {
93
99
rr .fnTicker .Stop ()
94
100
rr .fnTicker = time .NewTicker (rate .Rate )
95
101
}
0 commit comments