go - Is there a way to do repetitive tasks at intervals in Golang? -
is there way repetitive background tasks in go? i'm thinking of timer.schedule(task, delay, period)
in java. know can goroutine , time.sleep()
, i'd stopped.
here's got, looks ugly me. there 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) }
the function time.newticker
makes channel sends periodic message, , provides way stop it. use (untested):
ticker := time.newticker(5 * time.second) quit := make(chan struct{}) go func() { { select { case <- ticker.c: // stuff case <- quit: ticker.stop() return } } }()
you can stop worker closing quit
channel: close(quit)
.
Comments
Post a Comment