Created
December 26, 2018 07:28
-
-
Save hackerzhut/cb64142c62c7ce944f4cc5814f60e54c to your computer and use it in GitHub Desktop.
Timer
This file contains hidden or 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
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