Ready Steady GO: Call Function Periodically With Timeout
August 16, 2020 | 1 min read | 1,522 views
In this post, I introduce a golang example code that calls some function periodically for a specified amount of time. It was a good exercise for a beginner like me to use goroutines.
The sample code consists of the 3 elements.
- Write a function
preiodicGreet()
that prints a given message periodycally - Set a timeout context in the main function
- Call the function
preiodicGreet()
as a goroutine in the main function
package main
import (
"context"
"fmt"
"time"
)
func periodicGreet(msg string, period time.Duration) {
t := time.NewTicker(period * time.Second)
defer t.Stop()
for {
select {
case <-t.C: // Activate periodically
fmt.Printf(msg)
}
}
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second) // Cancel in 5 seconds
defer cancel()
go periodicGreet("Hello, World!\n", 1) // Call as a goroutine
select {
case <-ctx.Done(): // When time is out
fmt.Println("Periodic greeting done")
}
}
References
Written by Shion Honda. If you like this, please share!