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
+4.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+8.7k Golang : Sort and reverse sort a slice of integers
+17.1k Golang : Logging with logrus
+23.7k Golang : Convert long hexadecimal with strconv.ParseUint example
+8.2k Golang : Extract or copy items from map based on value
+13.7k Golang : Get all local users and print out their home directory, description and group id
+10.7k Golang : md5 hash of a string
+7k Golang : Add build version and other information in executables
+8.8k Golang : Detect number of faces or vehicles in a photo
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.
+4.4k Golang : If else example and common mistake