patterngoCritical
Is there a way to do repetitive tasks at intervals?
Viewed 0 times
intervalstasksrepetitivewaythere
Problem
Is there a way to do repetitive background tasks in Go? I'm thinking of something like
Here's what I got, but looks ugly to me. Is there a cleaner/better way?
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)
}Solution
The function
You can stop the worker by closing the
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).Code Snippets
ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <- ticker.C:
// do stuff
case <- quit:
ticker.Stop()
return
}
}
}()Context
Stack Overflow Q#16466320, score: 344
Revisions (0)
No revisions yet.