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.5k Golang : How to check if your program is running in a terminal
+18.7k Golang : Delete duplicate items from a slice/array
+4.6k Adding Skype actions such as call and chat into web page examples
+51.8k Golang : How to get time in milliseconds?
+8.3k Your page has meta tags in the body instead of the head
+5.9k Golang : Shuffle array of list
+14.7k Golang : Normalize unicode strings for comparison purpose
+19.2k Golang : Calculate entire request body length during run time
+9.7k Golang : Qt get screen resolution and display on center example
+17.5k Golang : Clone with pointer and modify value
+5.7k Linux/Unix/PHP : Restart PHP-FPM
+9.7k Golang : Load ASN1 encoded DSA public key PEM file example