Created
August 30, 2019 10:12
-
-
Save J7mbo/e3a3d4aa090df809ea6a9ef4ba9ae104 to your computer and use it in GitHub Desktop.
Goroute, single running, cancellable, running on an interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
manager := make(chan struct{}) | |
_ = publisher(manager) | |
time.Sleep(10 * time.Second) | |
close(manager) | |
} | |
func publisher(manager chan struct{}) chan<- struct{} { | |
pubch := make(chan struct{}) | |
printerCh := printer(manager) | |
go func() { | |
ticker := time.NewTicker(2 * time.Second).C | |
defer fmt.Println("Stopping Publisher.") | |
defer close(printerCh) | |
for { | |
select { | |
case <- manager: | |
return | |
case <- pubch: | |
return | |
case <- ticker: | |
printerCh <- struct{}{} | |
} | |
} | |
}() | |
return pubch | |
} | |
// <- means externally it's write only | |
func printer(manager chan struct{}) chan<- struct{} { | |
ch := make(chan struct{}) | |
go func() { | |
for { | |
select { | |
case <-manager: | |
return | |
case <-ch: | |
fmt.Println("Sleeping for 5 seconds") | |
time.Sleep(time.Duration(5 * time.Second)) | |
} | |
} | |
}() | |
return ch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment