Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 10, 2013 06:52
Show Gist options
  • Save physacco/5127435 to your computer and use it in GitHub Desktop.
Save physacco/5127435 to your computer and use it in GitHub Desktop.
This demonstrates usage of timer in go. Both one-shot timer and periodic timer. In the periodic timer example, goroutine and select are used.
package main
import (
"fmt"
"time"
)
// The timeout handler.
func ontimeout(t time.Time) {
fmt.Println("[timeout] ", t)
}
// Schedule callback every interval milliseconds.
func periodic_timer(interval time.Duration,
callback func(time.Time)) {
var timer *time.Timer
for {
// Creates a new Timer that will send the current time on
// its channel C after (at least) the specified duration.
timer = time.NewTimer(interval * time.Millisecond)
// Wait for timeout.
select {
case t := <-timer.C:
ontimeout(t)
}
}
}
func main() {
// Run periodic_timer in main goroutine
// periodic_timer(1000, ontimeout)
// Run periodic_timer in another goroutine
go periodic_timer(1000, ontimeout) // [1]
for {
// the main goroutine has to sleep so that [1] could run
time.Sleep(5000 * time.Millisecond)
}
}
package main
import (
"log"
"time"
)
func ontimeout() {
log.Println("timeout is occurred")
}
func main() {
for {
// AfterFunc waits for the duration to elapse and then calls f
// in its own goroutine. It returns a Timer that can be used to
// cancel the call using its Stop method.
timer := time.AfterFunc(1000 * time.Millisecond, ontimeout)
log.Println("timer installed: ", timer)
time.Sleep(5000 * time.Millisecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment