Skip to content

Commit

Permalink
fix scheduler restart (#825)
Browse files Browse the repository at this point in the history
  • Loading branch information
27149chen authored Feb 7, 2025
1 parent 8c70fdc commit a757eff
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
20 changes: 16 additions & 4 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,8 @@ func (s *scheduler) stopScheduler() {
for _, j := range s.jobs {
j.stop()
}
for id, j := range s.jobs {
for _, j := range s.jobs {
<-j.ctx.Done()

j.ctx, j.cancel = context.WithCancel(s.shutdownCtx)
s.jobs[id] = j
}
var err error
if s.started {
Expand All @@ -254,6 +251,21 @@ func (s *scheduler) stopScheduler() {
err = ErrStopExecutorTimedOut
}
}
for id, j := range s.jobs {
oldCtx := j.ctx
if j.parentCtx == nil {
j.parentCtx = s.shutdownCtx
}
j.ctx, j.cancel = context.WithCancel(j.parentCtx)

// also replace the old context with the new one in the parameters
if len(j.parameters) > 0 && j.parameters[0] == oldCtx {
j.parameters[0] = j.ctx
}

s.jobs[id] = j
}

s.stopErrCh <- err
s.started = false
s.logger.Debug("gocron: scheduler stopped")
Expand Down
49 changes: 49 additions & 0 deletions scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,55 @@ func TestScheduler_StopLongRunningJobs(t *testing.T) {
})
}

func TestScheduler_StopAndStartLongRunningJobs(t *testing.T) {
t.Run("start, run job, stop jobs before job is completed", func(t *testing.T) {
s := newTestScheduler(t,
WithStopTimeout(50*time.Millisecond),
)

restart := false
restartP := &restart

_, err := s.NewJob(
DurationJob(
50*time.Millisecond,
),
NewTask(
func(ctx context.Context) {
select {
case <-ctx.Done():
if *restartP {
t.Fatal("job should not been canceled after restart")
}
case <-time.After(100 * time.Millisecond):
if !*restartP {
t.Fatal("job can not been canceled")
}

}
},
),
WithStartAt(
WithStartImmediately(),
),
WithSingletonMode(LimitModeReschedule),
)
require.NoError(t, err)

s.Start()

time.Sleep(20 * time.Millisecond)
// the running job is canceled, no unexpected timeout error
require.NoError(t, s.StopJobs())

*restartP = true

s.Start()

time.Sleep(200 * time.Millisecond)
})
}

func TestScheduler_Shutdown(t *testing.T) {
defer verifyNoGoroutineLeaks(t)

Expand Down

0 comments on commit a757eff

Please sign in to comment.