Documentation › JSON API › Running background tasks
A backgroundTask() helper is included in the cmd/api/helpers.go file. You can use this in your handlers, helpers and middleware to run any code in a separate background goroutine.
It’s useful for tasks you want to run after sending an HTTP response, such as sending emails or completing slow-running jobs.
When a graceful server shutdown is in progress, it will wait for any background tasks launched via backgroundTask() to finish, up to the maximum time defined in the defaultShutdownPeriod constant (which is defined in cmd/api/server.go and is 30 seconds by default).
To use it, you pass an anonymous function with the signature func() error to the backgroundTask() helper. This anonymous function should contain the code you want to execute in the background goroutine.
For example:
func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
...
app.backgroundTask(r, func() error {
// The logic you want to execute in a background task goes here.
// It should return an error, or nil.
err := doSomething()
if err != nil {
return err
}
return nil
})
...
}
If your anonymous function returns a non-nil error value, the backgroundTask() helper will pass the error to the reportServerError() helper in cmd/api/errors.go to be handled. If the code in your anonymous function panics, the backgroundTask() helper will recover the panic, and again pass the error to the reportServerError() to be handled.
You can change these behaviors if you want by editing the backgroundTask() code.