[core] gobot.Every function now returns a channel so it can be halted
Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
parent
bf43df59b5
commit
aab1461e0d
16
utils.go
16
utils.go
|
@ -23,17 +23,27 @@ var eventError = func(e *Event) (err error) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every triggers f every t time until the end of days. It does not wait for the
|
// Every triggers f every t time until the end of days, or when a
|
||||||
// previous execution of f to finish before it fires the next f.
|
// bool value is sent to the channel returned by the Every function.
|
||||||
func Every(t time.Duration, f func()) {
|
// It does not wait for the previous execution of f to finish before
|
||||||
|
// it fires the next f.
|
||||||
|
func Every(t time.Duration, f func()) chan bool {
|
||||||
|
done := make(chan bool)
|
||||||
c := time.Tick(t)
|
c := time.Tick(t)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
break
|
||||||
|
default:
|
||||||
<-c
|
<-c
|
||||||
go f()
|
go f()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
return done
|
||||||
}
|
}
|
||||||
|
|
||||||
// After triggers f after t duration.
|
// After triggers f after t duration.
|
||||||
|
|
|
@ -24,6 +24,18 @@ func TestEvery(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEveryWhenDone(t *testing.T) {
|
||||||
|
i := 0
|
||||||
|
done := Every(20*time.Millisecond, func() {
|
||||||
|
i++
|
||||||
|
})
|
||||||
|
<-time.After(20 * time.Millisecond)
|
||||||
|
done <- true
|
||||||
|
if i > 1 {
|
||||||
|
t.Error("Test should have stopped after 20ms")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAfter(t *testing.T) {
|
func TestAfter(t *testing.T) {
|
||||||
i := 0
|
i := 0
|
||||||
After(1*time.Millisecond, func() {
|
After(1*time.Millisecond, func() {
|
||||||
|
|
Loading…
Reference in New Issue