Skip to content

Instantly share code, notes, and snippets.

@anhnd3
Last active January 5, 2020 14:11
Show Gist options
  • Save anhnd3/33aef3faa178427e2de0189e3daad757 to your computer and use it in GitHub Desktop.
Save anhnd3/33aef3faa178427e2de0189e3daad757 to your computer and use it in GitHub Desktop.
Interval Function Golang
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)
}
package util
import (
"time"
)
// Scheduler ...
type Scheduler struct {
ticker *time.Ticker
quit chan struct{}
process func()
}
// NewScheduler ...
func NewScheduler(process func()) *Scheduler {
return &Scheduler{
ticker: time.NewTicker(time.Minute),
quit: make(chan struct{}),
process: process,
}
}
// Run ...
func (t *Scheduler) Run() {
for {
select {
case <-t.ticker.C:
go func() {
t.process()
}()
case <-t.quit:
t.ticker.Stop()
return
}
}
}
// Stop ...
func (t *Scheduler) Stop() {
close(t.quit)
}
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.Second, helloworld)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment