cron
cron copied to clipboard
context in cron.Job.Run Is it possible?
I want to pass in the context in cron.Job.Run, is there any way?
return cron.WithChain(func(job cron.Job) cron.Job {
return cron.FuncJob(func() {
// There is a way to write context
job.Run()
// use context
})
})
@robfig
The AddFunc
method should pass a context to the added function, as there might be websocket connections, or long-polling HTTP requests, that are open - and need to be cancelled when the task closes. Without this cancellation, these connections would remain open, and they would not be closed until the server was able to respond back, and therefore blocking additional connections that could be made. Please read https://go.dev/blog/context and https://pkg.go.dev/context for more information.
Example implementation
cron.New().AddFunc("", function (context c.Context) {
request.Context(context)
})
Example source code change
func (c *Cron) AddFunc(spec string, cmd func(context c.Context)) error {
return c.AddJob(spec, FuncJob(cmd))
}