-
-
Save umardx/e304f9d66f4acca13a73650e051837fb to your computer and use it in GitHub Desktop.
two ways to call a function every 2 seconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
var pCount int | |
ch := make(chan int, 5) | |
f := func(i int) { | |
defer func() { | |
if err := recover(); err != nil { | |
ch <- i | |
} | |
}() | |
fmt.Printf("goroutine f(%v) started\n", i) | |
time.Sleep(1000 * time.Millisecond) | |
panic("goroutine in panic") | |
} | |
go f(1) | |
go f(2) | |
go f(3) | |
go f(4) | |
for { | |
i := <-ch | |
pCount++ | |
if pCount >= 5 { | |
fmt.Println("Too many panics") | |
break | |
} | |
fmt.Printf("Detected goroutine f(%v) panic, will restart\n", i) | |
f(i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment