Part 1 , Part 2 , Part 3 , Part 4 , Part 5
Goroutines can be used to start independent long running task. These tasks can be entire microservices, which is very useful for creating a single application with multiple system responsibilities. The select statement will block and wait for a channel to be ready for reading, then after reading from the channel the code will be executed.
Playground: https://go.dev/play/p/8JwQDgNrHJY
package main
import (
"fmt"
"time"
)
// example of a long running go routine
func main() {
quit := make(chan struct{})
count := 1
// start a goroutine
// it will run until the quit channel is closed
// the quit channel is closed after 5 seconds
go func() {
// create a ticker
ticker := time.NewTicker(
1 * time.Second,
)
for {
// select will wait until one of the channels
// is ready to be read from
// if the quit channel is ready to be read from
// the goroutine will return
// if the ticker channel is ready to be read from
// the goroutine will execute the task
select {
// read from the ticker channel
// the ticker channel will be ready to be read from
// every second
case <-ticker.C:
// do a task
fmt.Println("Tick", count)
count++
// read from the quit channel
// the quit channel will be ready to be read from
// when it is closed
case <-quit:
// stop the goroutine by returning
fmt.Println("Stopping")
return
}
}
}()
// wait for 5 seconds
time.Sleep(5 * time.Second)
// stop the ticker
close(quit)
fmt.Println("Done")
}