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
+16.2k Golang : Check if a string contains multiple sub-strings in []string?
+8.8k Golang : automatically figure out array length(size) with three dots
+10.2k Android Studio : Simple input textbox and intercept key example
+15.3k Golang : Validate hostname
+20.4k Golang : Read directory content with os.Open
+7.5k Golang : Error reading timestamp with GORM or SQL driver
+37.7k Golang : Read a text file and replace certain words
+20.5k Golang : Convert PNG transparent background image to JPG or JPEG image
+37.4k Golang : Comparing date or timestamp
+17.2k Golang : Multi threading or run two processes or more example
+27.1k Golang : dial tcp: too many colons in address
+46k Golang : Marshal and unmarshal json.RawMessage struct example