Stay focused, be present

Coding

Golang: Two way to call a function every 2 seconds

These are two ways to call a function every 2 seconds, written by ryanfitz

Source: https://gist.github.com/ryanfitz/4191392

1. A simple way – golang-nuts

package main
import (
"fmt"
"time"
)
// Suggestions from golang-nuts
// http://play.golang.org/p/Ctg3_AQisl
func doEvery(d time.Duration, f func(time.Time)) {
for x := range time.Tick(d) {
f(x)
	}
}
func helloworld(t time.Time) {
	fmt.Printf("%v: Hello, World!\n", t)
}
func main() {
doEvery(2000*time.Millisecond, helloworld)
}

2. Another way – keeping service running using HandleFunc & ListenAndServe

package main

import (
	"fmt"
	"net/http"
	"time"
)

func doSomething(s string) {
	fmt.Println("doing something", s)
}
func startPolling1() {
	for {
		time.Sleep(2 * time.Second)
		go doSomething("from polling 1")
	}
}
func startPolling2() {
	for {
		<-time.After(2 * time.Second)
		go doSomething("from polling 2")
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])

}
func main() {
	go startPolling1()
	go startPolling2()
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8888", nil)
}

About author

always try to be better

Leave a Reply

Your email address will not be published. Required fields are marked *