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
+18.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+6.3k Golang : Rot13 and Rot5 algorithms example
+10k Golang : Concatenate (combine) buffer data example
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+5.8k Golang : Output or print out JSON stream/encoded data
+4k Golang : Print instead of building pyramids
+9.5k Golang : Roll the dice example
+14.1k Golang : Get query string value on a POST request
+18.2k Golang : Convert seconds to human readable time format example
+15.5k Golang : How to generate QR codes?
+14.6k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+12.8k Android Studio : Use image as AlertDialog title with custom layout example