Skip to content

Instantly share code, notes, and snippets.

@ryanfitz
Created December 2, 2012 22:45

Revisions

  1. Ryan Fitzgerald revised this gist Dec 2, 2012. 1 changed file with 23 additions and 0 deletions.
    23 changes: 23 additions & 0 deletions golang-nuts.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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)
    }
  2. Ryan Fitzgerald created this gist Dec 2, 2012.
    37 changes: 37 additions & 0 deletions polling.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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)
    }