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
+21.3k SSL : How to check if current certificate is sha1 or sha2
+9k Golang : How to get username from email address
+15.3k Golang : Get digits from integer before and after given position example
+10.8k Golang : How to determine a prime number?
+8.2k Golang : How to check variable or object type during runtime?
+22.2k Golang : Set and Get HTTP request headers example
+5.1k Javascript : Shuffle or randomize array example
+9.7k CodeIgniter : Load different view for mobile devices
+5.3k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+8.8k Golang : Get curl -I or head data from URL example
+12.9k Golang : Convert(cast) int to int64
+22.7k Golang : Read a file into an array or slice example