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)
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…