mirror of
https://github.com/sourcegraph/sourcegraph.git
synced 2026-02-06 16:11:57 +00:00
This PR is a result/followup of the improvements we've made in the [SAMS repo](https://github.com/sourcegraph/sourcegraph-accounts/pull/199) that allows call sites to pass down a context (primarily to indicate deadline, and of course, cancellation if desired) and collects the error returned from `background.Routine`s `Stop` method. Note that I did not adopt returning error from `Stop` method because I realize in monorepo, the more common (and arguably the desired) pattern is to hang on the call of `Start` method until `Stop` is called, so it is meaningless to collect errors from `Start` methods as return values anyway, and doing that would also complicate the design and semantics more than necessary. All usages of the the `background.Routine` and `background.CombinedRoutines` are updated, I DID NOT try to interpret the code logic and make anything better other than fixing compile and test errors. The only file that contains the core change is the [`lib/background/background.go`](https://github.com/sourcegraph/sourcegraph/pull/62136/files#diff-65c3228388620e91f8c22d91c18faac3f985fc67d64b08612df18fa7c04fafcd).
82 lines
1.4 KiB
Go
82 lines
1.4 KiB
Go
package goroutine
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
type exampleRoutine struct {
|
|
done chan struct{}
|
|
}
|
|
|
|
func (m *exampleRoutine) Name() string {
|
|
return "exampleRoutine"
|
|
}
|
|
|
|
func (m *exampleRoutine) Start() {
|
|
for {
|
|
select {
|
|
case <-m.done:
|
|
fmt.Println("done!")
|
|
return
|
|
default:
|
|
}
|
|
|
|
fmt.Println("Hello there!")
|
|
time.Sleep(200 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
func (m *exampleRoutine) Stop(context.Context) error {
|
|
m.done <- struct{}{}
|
|
return nil
|
|
}
|
|
|
|
func ExampleBackgroundRoutine() {
|
|
r := &exampleRoutine{
|
|
done: make(chan struct{}),
|
|
}
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
go func() {
|
|
err := MonitorBackgroundRoutines(ctx, r)
|
|
if err != nil {
|
|
fmt.Printf("error: %v\n", err)
|
|
}
|
|
}()
|
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
cancel()
|
|
time.Sleep(200 * time.Millisecond)
|
|
}
|
|
|
|
func ExamplePeriodicGoroutine() {
|
|
h := HandlerFunc(func(ctx context.Context) error {
|
|
fmt.Println("Hello from the background!")
|
|
return nil
|
|
})
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
r := NewPeriodicGoroutine(
|
|
ctx,
|
|
h,
|
|
WithName("example.background"),
|
|
WithDescription("example background routine"),
|
|
WithInterval(200*time.Millisecond),
|
|
)
|
|
|
|
go func() {
|
|
err := MonitorBackgroundRoutines(ctx, r)
|
|
if err != nil {
|
|
fmt.Printf("error: %v\n", err)
|
|
}
|
|
}()
|
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
cancel()
|
|
time.Sleep(200 * time.Millisecond)
|
|
}
|