Skip to content

Instantly share code, notes, and snippets.

@jbarber
Created July 7, 2014 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbarber/1e2e2cd98f3b3ade7e6d to your computer and use it in GitHub Desktop.
Save jbarber/1e2e2cd98f3b3ade7e6d to your computer and use it in GitHub Desktop.
Go routine on a changable timer
package main
/*
Example of creating go routine with time based channel - this time can be
adjusted by the parent, so it can postpone (or bring forwards) whatever the
child should do. This could be useful for creating a polling mechanism which
you occasionally want to run sooner.
The parent creates the channel and passes it to the go routine to wait for 10
seconds. This channel is used to communicate how long the child should wait
for. The child creates a channel to act as a timer, and selects on it and
the channel from the parent. This causes the child to wait for the original
timer to go off, or for a new timer to be sent from the parent.
*/
import (
"fmt"
"time"
)
func waiter(t chan time.Duration) {
n := make(<-chan time.Time)
for {
select {
case <-n:
fmt.Println("Child: timer triggered")
close(t)
return
case v := <-t:
n = time.After(v)
fmt.Printf("Child: new time seen - %s\n", v)
break
}
}
}
func main() {
two_seconds := 2 * time.Second
t := make(chan time.Duration)
go waiter(t)
t <- (10 * time.Second)
fmt.Printf("Parent: sleeping for %s\n", two_seconds)
time.Sleep(two_seconds)
fmt.Println("Parent: sending new sleep")
t <- two_seconds
fmt.Println("Parent: sleep sent, waiting for child")
_, open := <-t
fmt.Printf("Parent: child responded: %s\n", open)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment