Skip to content

Instantly share code, notes, and snippets.

@ryanfitz
Created December 2, 2012 22:45
Show Gist options
  • Save ryanfitz/4191392 to your computer and use it in GitHub Desktop.
Save ryanfitz/4191392 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)
}
@openjr
Copy link

openjr commented Dec 15, 2015

You just saved me, thanks for posting this!

@ZhenhangTung
Copy link

Wow, the way of keeping service running using HandleFunc & ListenAndServe is very clever. I've never thought about that.

@moehandi
Copy link

Nice, for what Im looking for

@arnonuem
Copy link

Thank you for posting this ;)
And thank you search engines for indexing this post :D

@LihuaWu
Copy link

LihuaWu commented Jan 18, 2018

why not just using something like select{} or waitgroup?

@ssingh-continuum
Copy link

Thank you for posting...

@gmcnicol
Copy link

Great.

@Parth
Copy link

Parth commented Jun 26, 2018

doEvery(20*time.Millisecond, helloworld)

calls helloworld every 0.02 seconds, not every 2 seconds

@zhurasique
Copy link

ty, still good solution for 2020, haha

@IgorDePaula
Copy link

How to stop the polling?

@q42jaap
Copy link

q42jaap commented Sep 24, 2020

@IgorDePaula take a look at this playground:
https://play.golang.org/p/l_9R0d71iIJ
I've altered the time.Tick solution to use a select together with Context.

@IgorDePaula
Copy link

@q42jaap Thank you

@IGNRexI
Copy link

IGNRexI commented Nov 14, 2021

thanks <3

@SaraTahiri97
Copy link

Thank you !

@perebaj
Copy link

perebaj commented Jan 18, 2024

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment