cron
cron copied to clipboard
Cancellation support
Right now, this library does not seem to have built-in support for cancellation. I feel like this is something that is probably needed by ~90% of use-cases, even if it's for something as simple as being able to quit the program on SIGTERM. I've been able to work around this by creating a wrapper around the library like this:
package scheduler
import (
"context"
"github.com/robfig/cron"
)
type Job interface {
// Run executes the cron task. It should cancel whatever it
// is doing upon receiving a signal from ctx.Done.
Run(context.Context)
}
// CronScheduler can run tasks on a cron schedule, with cancellation.
type CronScheduler struct {
runner *cron.Cron
}
func NewCronScheduler() *CronScheduler {
return &CronScheduler{runner: cron.New()}
}
func (s *CronScheduler) Run(ctx context.Context) {
go func() { s.runner.Run() }()
for range ctx.Done() {
s.runner.Stop()
return
}
}
// bit of a hack so that we can pass a context into cron.Schedule
type jobWrapper struct {
ctx context.Context
runFunc func(context.Context)
}
func (j *jobWrapper) Run() {
j.runFunc(j.ctx)
}
func (s *CronScheduler) Schedule(ctx context.Context, schedule cron.Schedule, job Job) {
wrapper := &jobWrapper{
ctx: ctx,
runFunc: job.Run,
}
s.runner.Schedule(schedule, wrapper)
}
It would be really great if the interfaces provided by this library accepted contexts to support cancellation, deadlines, etc.
Hope for the built-in support.
There is Remove function to cancel job: https://github.com/robfig/cron/blob/master/cron.go#L204