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
+11.9k Golang : Verify Linux user password again before executing a program example
+45.2k Golang : Use wildcard patterns with filepath.Glob() example
+7.1k Nginx : Password protect a directory/folder
+6.9k Golang : Calculate pivot points for a cross
+15.2k Golang : Search folders for file recursively with wildcard support
+18.6k Golang : Example for RSA package functions
+28.7k Golang : Change a file last modified date and time
+13.7k Golang : Query string with space symbol %20 in between
+31.1k Golang : Interpolating or substituting variables in string examples
+10.8k Golang : Underscore string example
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example