Skip to content

Instantly share code, notes, and snippets.

@automaticalldramatic
Forked from ryanfitz/golang-nuts.go
Last active September 3, 2019 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save automaticalldramatic/e727c9d0ab6537ac9e4b698b66b90da5 to your computer and use it in GitHub Desktop.
Save automaticalldramatic/e727c9d0ab6537ac9e4b698b66b90da5 to your computer and use it in GitHub Desktop.
two ways to call a function every 2 seconds
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(20*time.Millisecond, helloworld)
}
package main
import (
"fmt"
"time"
"net/http"
)
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(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment