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
+8k Golang : HTTP Server Example
+3.9k Detect if Google Analytics and Developer Media are loaded properly or not
+17.1k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+10.8k Golang : Replace a parameter's value inside a configuration file example
+5.2k Golang : Get FX sentiment from website example
+6.9k Golang : Takes a plural word and makes it singular
+9.9k Golang : Identifying Golang HTTP client request
+3.6k Golang : Switch Redis database redis.NewClient
+7.6k Golang : Generate human readable password
+13.9k Javascript : Prompt confirmation before exit
+4.5k Linux : sudo yum updates not working