Golang : Execute function at intervals or after some delay
Problem :
You want to execute functions at intervals - such as polling a remote terminal every 30 seconds or count the number of processes running in the memory after 10 seconds.
Solution :
Use the time.Tick()
function. For example :
package main
import (
"fmt"
"time"
)
func pollRemoteTerm(n time.Duration) {
timestamp := time.Now().Local()
for _ = range time.Tick(n * time.Second) {
str := "Polling remote terminal data at <some remote terminal name> at "+ timestamp.String()
fmt.Println(str)
}
}
func main() {
go pollRemoteTerm(10) // very useful for interval polling
select {} // this will cause the program to run forever
}
See also : Golang : Call a function after some delay(time.Sleep and Tick)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.7k Golang : Create and resolve(read) symbolic links
+11k Golang : How do I get the local IP (non-loopback) address ?
+9k Golang : Get IP addresses of a domain name
+2.3k Javascript : How to loop over and parse JSON data?
+6.2k Golang : Get constant name from value
+11.3k Golang : Time slice or date sort and reverse sort example
+3.4k Golang : Combine slices but preserve order example
+2.4k Unix/Linux/MacOSx : Get local IP address
+5.5k Golang : Print UTF-8 fonts on image example
+4.2k Golang : Test a slice of integers for odd and even numbers
+11.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+2.6k Golang : Extract XML attribute data with attr field tag example