Skip to content

Instantly share code, notes, and snippets.

@hackerzhut
Created December 26, 2018 07:28
Show Gist options
  • Save hackerzhut/cb64142c62c7ce944f4cc5814f60e54c to your computer and use it in GitHub Desktop.
Save hackerzhut/cb64142c62c7ce944f4cc5814f60e54c to your computer and use it in GitHub Desktop.
Timer
func keepRunning(timeout int, action func(), cancel <-chan os.Signal) {
ticker := time.NewTicker(500 * time.Millisecond)
for {
select {
case <-cancel:
fmt.Printf("exiting. timed out\n")
ticker.Stop()
return
case <-ticker.C:
action()
fmt.Println("ticking now")
}
}
}
// NewTimer creates a timer that runs for a specified number of seconds.
// When timer finishes, it calls the action function supplied.
// Use the returned timer object to stop the timer early, if needed.
func NewTimer(seconds int, action func()) *time.Timer {
timer := time.NewTimer(time.Second * time.Duration(seconds))
go func() {
<-timer.C
action()
}()
return timer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment