forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slowmessage.go
34 lines (28 loc) · 885 Bytes
/
slowmessage.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
package slowmessage
import (
"time"
)
// SlowFunc is the function that could be slow. Usually, you'll have to
// wrap an existing function in a lambda to make it match this type signature.
type SlowFunc func() error
// CallbackFunc is the function that is triggered when the threshold is reached.
type CallbackFunc func()
// Do calls sf. If threshold time has passed, cb is called. Note that this
// call will be made concurrently to sf still running.
func Do(threshold time.Duration, sf SlowFunc, cb CallbackFunc) error {
// Call the slow function
errCh := make(chan error, 1)
go func() {
errCh <- sf()
}()
// Wait for it to complete or the threshold to pass
select {
case err := <-errCh:
return err
case <-time.After(threshold):
// Threshold reached, call the callback
cb()
}
// Wait an indefinite amount of time for it to finally complete
return <-errCh
}