Skip to content

cancel running jobs if possible when run Scheduler.StopJobs()#819

Merged
JohnRoesler merged 3 commits intogo-co-op:v2from
27149chen:cancel-running-job-when-run-StopJobs
Jan 23, 2025
Merged

cancel running jobs if possible when run Scheduler.StopJobs()#819
JohnRoesler merged 3 commits intogo-co-op:v2from
27149chen:cancel-running-job-when-run-StopJobs

Conversation

@27149chen
Copy link
Contributor

@27149chen 27149chen commented Jan 23, 2025

What does this do?

when run Scheduler.StopJobs(), the scheduler will wait for the running jobs to be completed. If there are long running jobs, it will always return "timed out waiting for jobs to finish".

This pr try to cancel the running jobs if possible

Which issue(s) does this PR fix/relate to?

Resolves #818

List any changes that modify/break current functionality

You can now add a task function which accept ctx as the first param, but you do need pass a ctx actually, gocron will handle it properly

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
		),
	)

but if you have you own ctx, fell free to pass it

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
                         ctx,
		),
	)

or you can also pass it as a job option to control the whole thing

	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(ctx context.Context) {
				// do things
			},
		),
                gocron.WithContext(ctx)
	)

Have you included tests for your changes?

yes

Did you document any new/modified functionality?

  • Updated example_test.go
  • Updated README.md

Notes

Signed-off-by: lou <alex1988@outlook.com>
Signed-off-by: lou <alex1988@outlook.com>
Copy link
Contributor

@JohnRoesler JohnRoesler left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @27149chen this is a great addition. Some things that will be needed still:

  • addition of the new method to example_test.go
  • additional comments on the NewJob and NewTask functions explaining that if your task accepts a context as it's first parameter, gocron will pass in a context you can listen to for cancellation. Also, updating the example_test.go for the NewTask

I will make a PR to address.

@JohnRoesler JohnRoesler merged commit 50966c7 into go-co-op:v2 Jan 23, 2025
4 checks passed
@27149chen 27149chen mentioned this pull request Feb 6, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] - A long running job can not be cancelled when run s.StopJobs()

2 participants