Tuesday 29 November 2016

go - Is there a way to do repetitive tasks at intervals?



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)
}

Answer



The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):




ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <- ticker.C:
// do stuff
case <- quit:
ticker.Stop()

return
}
}
}()


You can stop the worker by closing the quit channel: close(quit).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...