Skip to content

Commit

Permalink
fix deadlock when starting / stopping the scheduler (#369)
Browse files Browse the repository at this point in the history
* fix deadlock when starting / stopping the scheduler

* add mutex to stop chan
  • Loading branch information
JohnRoesler authored Aug 4, 2022
1 parent 08a53ef commit 772979f
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ type Scheduler struct {
singletonMode bool // defaults all jobs to use SingletonMode()
jobCreated bool // so the scheduler knows a job was created prior to calling Every or Cron

stopChan chan struct{} // stops the scheduler
startBlockingStopChanMutex sync.Mutex
startBlockingStopChan chan struct{} // stops the scheduler
}

// days in a week
Expand All @@ -54,7 +55,6 @@ func NewScheduler(loc *time.Location) *Scheduler {
time: &trueTime{},
executor: &executor,
tagsUnique: false,
stopChan: make(chan struct{}, 1),
}
}

Expand All @@ -69,7 +69,10 @@ func (s *Scheduler) SetMaxConcurrentJobs(n int, mode limitMode) {
// This blocking method can be stopped with Stop() from a separate goroutine.
func (s *Scheduler) StartBlocking() {
s.StartAsync()
<-s.stopChan
s.startBlockingStopChanMutex.Lock()
s.startBlockingStopChan = make(chan struct{}, 1)
s.startBlockingStopChanMutex.Unlock()
<-s.startBlockingStopChan
}

// StartAsync starts all jobs without blocking the current thread
Expand Down Expand Up @@ -815,7 +818,7 @@ func (s *Scheduler) stop() {
s.setRunning(false)
s.stopJobs(s.jobs)
s.executor.stop()
s.stopChan <- struct{}{}
s.StopBlockingChan()
}

func (s *Scheduler) stopJobs(jobs []*Job) {
Expand Down Expand Up @@ -1299,3 +1302,11 @@ func (s *Scheduler) StartImmediately() *Scheduler {
func (s *Scheduler) CustomTime(customTimeWrapper TimeWrapper) {
s.time = customTimeWrapper
}

func (s *Scheduler) StopBlockingChan() {
s.startBlockingStopChanMutex.Lock()
if s.startBlockingStopChan != nil {
s.startBlockingStopChan <- struct{}{}
}
s.startBlockingStopChanMutex.Unlock()
}

0 comments on commit 772979f

Please sign in to comment.