Skip to content

Commit

Permalink
fix the warnings for go test --race
Browse files Browse the repository at this point in the history
  • Loading branch information
xwjdsh committed Feb 10, 2022
1 parent 52baf5b commit 99598cb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
run: go get -u github.com/mattn/goveralls

- name: Test
run: go test -v -covermode=count -coverprofile=coverage.out ./...
run: go test --race -v -covermode=atomic -coverprofile=coverage.out ./...

- name: Update Coveralls
env:
Expand Down
22 changes: 20 additions & 2 deletions tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ import (
// Task contains the scheduled task details and control mechanisms. This struct is used during the creation of tasks.
// It allows users to control how and when tasks are executed.
type Task struct {
sync.Mutex

// id is the Unique ID created for each task. This ID is generated by the Add() function.
id string

Expand Down Expand Up @@ -139,6 +141,14 @@ type Task struct {
cancel context.CancelFunc
}

// safeOps safely change task's data
func (t *Task) safeOps(f func()) {
t.Lock()
defer t.Unlock()

f()
}

// Scheduler stores the internal task list and provides an interface for task management.
type Scheduler struct {
sync.RWMutex
Expand Down Expand Up @@ -243,6 +253,10 @@ func (schd *Scheduler) Del(name string) {

// Stop the task
defer t.cancel()

t.Lock()
defer t.Unlock()

if t.timer != nil {
defer t.timer.Stop()
}
Expand Down Expand Up @@ -290,7 +304,9 @@ func (schd *Scheduler) Stop() {
func (schd *Scheduler) scheduleTask(t *Task) {
select {
case <-time.After(time.Until(t.StartAfter)):
t.timer = time.AfterFunc(t.Interval, func() { schd.execTask(t) })
t.safeOps(func() {
t.timer = time.AfterFunc(t.Interval, func() { schd.execTask(t) })
})
return
case <-t.ctx.Done():
return
Expand All @@ -309,6 +325,8 @@ func (schd *Scheduler) execTask(t *Task) {
}
}()
if !t.RunOnce {
t.timer.Reset(t.Interval)
t.safeOps(func() {
t.timer.Reset(t.Interval)
})
}
}

0 comments on commit 99598cb

Please sign in to comment.