Skip to content

Commit

Permalink
feat: implement Manager.Close()
Browse files Browse the repository at this point in the history
  • Loading branch information
robertrossmann committed Mar 6, 2024
1 parent 5188785 commit c98b738
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
16 changes: 16 additions & 0 deletions background.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package background

import (
"context"
"sync"
"time"

"github.com/kamilsk/retry/v5"
Expand Down Expand Up @@ -95,6 +96,21 @@ func (m *Manager) Cancel() {
m.loopmgr.cancel()
}

// Close is a convenience method that calls Wait() and Cancel() in parallel. It blocks until all tasks have finished.
func (m *Manager) Close() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
m.Wait()
wg.Done()
}()
go func() {
m.Cancel()
wg.Done()
}()
wg.Wait()
}

// CountOf returns the number of tasks of the specified type that are currently running. When the TaskType is invalid it
// returns 0.
func (m *Manager) CountOf(t TaskType) int {
Expand Down
33 changes: 33 additions & 0 deletions background_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,3 +389,36 @@ func Test_CountOf(t *testing.T) {
assert.Equal(t, 0, m.CountOf(background.TaskTypeLoop))
assert.Equal(t, 0, m.CountOf(background.TaskType(3)))
}

func Test_Close(t *testing.T) {
m := background.NewManager()
proceed := make(chan bool, 1)

def := background.Task{
Type: background.TaskTypeLoop,
Fn: func(ctx context.Context) error {
<-proceed
return nil
},
}
m.RunTask(context.Background(), def)
def = background.Task{
Type: background.TaskTypeOneOff,
Fn: func(ctx context.Context) error {
<-proceed
return nil
},
}
m.RunTask(context.Background(), def)
assert.Equal(t, 1, m.CountOf(background.TaskTypeOneOff))
assert.Equal(t, 1, m.CountOf(background.TaskTypeLoop))

go func() {
proceed <- true
proceed <- true
}()

m.Close()
assert.Equal(t, 0, m.CountOf(background.TaskTypeOneOff))
assert.Equal(t, 0, m.CountOf(background.TaskTypeLoop))
}

0 comments on commit c98b738

Please sign in to comment.