-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
70 lines (58 loc) · 1.58 KB
/
loop.go
File metadata and controls
70 lines (58 loc) · 1.58 KB
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
// Copyright (C) 2021 Creditor Corp. Group.
// See LICENSE for copying information.
package thelooper
import (
"context"
"errors"
"time"
)
// ErrCtxCancelled is error returned by loop when context cancelled.
var ErrCtxCancelled = errors.New("context cancelled")
// Loop implements a controllable recurring event.
type Loop struct {
interval time.Duration
ticker *time.Ticker
stop chan struct{}
}
// NewLoop creates a new loop with the specified interval.
func NewLoop(interval time.Duration) *Loop {
loop := &Loop{}
loop.SetInterval(interval)
return loop
}
// SetInterval allows to change the interval before starting.
// The interval is specified in milliseconds. 1 sec = 1000 millisec.
func (loop *Loop) SetInterval(interval time.Duration) {
loop.interval = interval * time.Millisecond
}
// SetNextTickDuration allows to change the next tick duration after starting.
func (loop *Loop) SetNextTickDuration(nextTick time.Time) {
loop.ticker = time.NewTicker(nextTick.Sub(time.Now().UTC()))
}
// Run runs the specified in an interval.
// Every interval `fn` is started.
func (loop *Loop) Run(ctx context.Context, fn func(ctx context.Context) error) error {
loop.stop = make(chan struct{})
defer close(loop.stop)
loop.ticker = time.NewTicker(loop.interval)
defer loop.ticker.Stop()
if err := fn(ctx); err != nil {
return err
}
for {
select {
case <-ctx.Done():
return ErrCtxCancelled
case <-loop.stop:
return nil
case <-loop.ticker.C:
if err := fn(ctx); err != nil {
return err
}
}
}
}
// Close closes the loop.
func (loop *Loop) Close() {
<-loop.stop
}