Is there a way to do repetitive background tasks in Go? I'm thinking of something like Timer.schedule(task, delay, period)
in Java. I know I can do this with a goroutine and Time.sleep()
, but I'd like something that easily stopped.
Here's what I got, but looks ugly to me. Is there a cleaner/better way?
func oneWay() {
var f func()
var t *time.Timer
f = func () {
fmt.Println("doing stuff")
t = time.AfterFunc(time.Duration(5) * time.Second, f)
}
t = time.AfterFunc(time.Duration(5) * time.Second, f)
defer t.Stop()
//simulate doing stuff
time.Sleep(time.Minute)
}
转载于:https://stackoverflow.com/questions/16466320/is-there-a-way-to-do-repetitive-tasks-at-intervals-in-golang