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
+19.5k Golang : Archive directory with tar and gzip
+10.5k Golang : Get currencies exchange rates example
+6.2k Golang : Selection sort example
+35.9k Golang : How to split or chunking a file to smaller pieces?
+11.1k Golang : Byte format example
+12.2k Elastic Search : Return all records (higher than default 10)
+10.3k Golang : Create matrix with Gonum Matrix package example
+29k Golang : Saving(serializing) and reading file with GOB
+12.1k Golang : Display list of countries and ISO codes
+22.3k Generate checksum for a file in Go
+13.1k Golang : Linear algebra and matrix calculation example
+4.4k JavaScript : Rounding number to decimal formats to display currency