cron icon indicating copy to clipboard operation
cron copied to clipboard

context in cron.Job.Run Is it possible?

Open Breezess opened this issue 4 years ago • 1 comments

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 
	})
})

Breezess avatar Jun 05 '20 08:06 Breezess

@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))
}

ex-tag avatar Mar 04 '22 05:03 ex-tag