-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepeat.go
63 lines (56 loc) · 1.4 KB
/
repeat.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
// Tideland Go Actor
//
// Copyright (C) 2019-2023 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package actor // import "tideland.dev/go/actor"
//--------------------
// IMPORTS
//--------------------
import (
"context"
"time"
)
//--------------------
// REPEAT
//--------------------
// RepeatWithContext runs an Action in a given interval. It will
// be done asynchronously until the context is canceled or timeout, the
// returned stopper function is called or the Actor is stopped.
func (act *Actor) RepeatWithContext(
ctx context.Context,
interval time.Duration,
action Action) (func(), error) {
if act.Err() != nil {
return nil, act.Err()
}
ctx, cancel := context.WithCancel(ctx)
// Goroutine to run the interval.
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-act.Done():
return
case <-ctx.Done():
return
case <-ticker.C:
if act.DoAsyncWithContext(ctx, action) != nil {
return
}
}
}
}()
return cancel, nil
}
// Repeat runs an Action in a given interval. It will
// be done asynchronously until the returned stopper function
// is called or the Actor is stopped.
func (act *Actor) Repeat(
interval time.Duration,
action Action) (func(), error) {
return act.RepeatWithContext(context.Background(), interval, action)
}
// EOF