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
+14.1k Golang : concatenate(combine) strings
+14.6k Golang : How to pass map to html template and access the map's elements
+8.8k Golang : Random integer with rand.Seed() within a given range
+7.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+28.9k Golang : Detect (OS) Operating System
+12.5k Elastic Search : Return all records (higher than default 10)
+10.6k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+8.7k Golang : Progress bar with ∎ character
+4.2k Javascript : Empty an array example
+31.7k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+29.2k Golang : Get first few and last few characters from string
+7.9k Golang : Load DSA public key from file example