Please see the following example.
type runner struct{}
func (r *runner) StopProcessing() {
// how to stop?
}
func (r *runner) StartProcessing() {
go func() {
for {
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
}
}()
}
As you can see I have a struct which does stuff, it's "running". It starts running when I call the run.StartProcessing()
method. It then fires an endless running for{}
-loop in a goroutine. Great, but I also want to be able to stop this process. And I really don't know how to achieve this. Any help is highly appreciated.
By using a channel to signal when to break out of a goroutine. The relevant part of your code would look something like this
type runner struct {
stop chan bool
}
func (r *runner) StopProcessing() {
r.stop <- true
}
func (r *runner) StartProcessing() {
r.stop = make(chan bool)
go func() {
for {
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
select {
case _ = <-r.stop:
close(r.stop)
return
default:
}
}
}()
}
You can see a full example here https://play.golang.org/p/OUn18Cprs0I
You might try something like this... You might not need atomic but this works.
package main
import (
"fmt"
"time"
"sync/atomic"
)
var trip = int64(0)
type runner struct{}
func (r *runner) StopProcessing() {
atomic.AddInt64(&trip, 1)
}
func (r *runner) StartProcessing() {
go func() {
for {
if trip > 0 {
break
}
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
}
}()
}
func newRunner() *runner {
return &runner{}
}
func main() {
run := newRunner()
run.StartProcessing()
// now wait 4 seconds and the kill the process
time.Sleep(4 * time.Second)
run.StopProcessing()
}
You can use a context to get timeouts and cancelation, without requiring any extra API.
type runner struct{}
func (r *runner) StartProcessing(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
}
}()
}
This gives you the flexibility to set a timeout, or cancel it at any time. You can also make use of existing contexts which may want to timeout or cancel sooner without your knowledge.
// normal timeout after 10 seconds
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
run.StartProcessing(ctx)
// decide to cancel early
time.Sleep(3 * time.Second)
cancel()