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
+5.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+24.6k Golang : Get executable name behind process ID example
+7.9k Golang : HTTP Routing with Goji example
+8.9k Golang : Setting variable value with ldflags
+5.5k Golang : Combine slices of complex numbers and operation example
+6k Golang : Get Alexa ranking data example
+12.6k Javascript : Prompt confirmation before exit
+5k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+14k Golang : Get timezone offset from date or timestamp
+24.8k Golang : Convert(cast) string to uint8 type and back to string
+23.5k Golang : convert rune to integer value
+10.7k Golang : Calculations using complex numbers example