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
+32.7k Golang : Proper way to set function argument default value
+6.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+11k Golang : 2 dimensional array example
+6.7k Golang : Ways to recover memory during run time.
+19.7k Curl usage examples with Golang
+15.1k Golang : Test floating point numbers not-a-number and infinite example
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+28k Golang : missing Git command
+4.6k How to check with curl if my website or the asset is gzipped ?
+7.3k Golang : How to check variable or object type during runtime?
+7.3k Swift : Convert (cast) Character to Integer?
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example